Adding ID and title to URL slugs in ASP.NET MVC

后端 未结 5 892
甜味超标
甜味超标 2020-12-04 07:34

How do you redirect a request in ASP.NET MVC to its correct canonical version if part of the URL is missing?

Using Stack Overflow as an example, the site adds the qu

5条回答
  •  心在旅途
    2020-12-04 07:42

    Here is an example of how they might do it, but I believe your asking how it can be done and this should work.

    First stage is to set-up 2 routes in the Global.asax

    routes.MapRoute("WithQuestion", "questions/{id}/{name}", new { controller = "Questions", action = "Question", id = "1" });
    routes.MapRoute("WithoutQuestion", "questions/{id}", new { controller = "Questions", action = "WithoutQuestion", id="1"});
    

    Now in our Questions controller,

        public ActionResult Question(int id)
        {
            //Load the question as we have the name appended.
            // We could actually do a little validation here as well
            return View();
        }
    
        public ActionResult WithoutQuestion(int id)
        {
            //Load the question object
            //Generate the full URL and redirect
            return Redirect(FullURL)
        }
    

    This is a very basic example but shows how you could do it.

提交回复
热议问题