Adding Redundant Information to a MVC Route

雨燕双飞 提交于 2019-12-03 16:04:46
Garry Shutler

Taking the example of a Stack Overflow question like this one the URL is:

so.com/questions/1142480/adding-redundant-information-to-a-mvc-route

However, the functional part of the URL is:

so.com/questions/1142480

The way this is achieved is by defining a route like this:

routes.MapRoute(
    "questions",
    "questions/{id}/{title}",
    new { controller = "Questions", action = "Details", title = "" });

You then create a link to it like this:

<%= Html.RouteLink("Adding Redundant Information to a MVC Route", 
        new 
        { 
            controller = "Questions", 
            id = 1142480, 
            title = "adding-redundant-information-to-a-mvc-route" 
        }
    )
%>

I would imagine the URL title is created from the actual title by lower casing, replacing spaces with dashes and a couple of other things (escaping/striping bad characters).

So long as your SEO route appears before any other matching route the SEO route will be used.

For complete clarity the controller would actually be like this:

public class QuestionsController : Controller
{
    public ActionResult Details(int id)
    {
        // stuff for display - notice title is not used
    }
}
Jon Limjap

One thing you should realize is that the text at the end of this URL is actually a dummy. For example, this URL:

will open this question cleanly. Similarly, a title other than your question:

will ALSO open this question without errors.

You can easily use some title-parsing algorithm to generate an "SEO friendly" URL for you complete with the title, and add it at the end of the question number. Your MVC route will just ignore the last part.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!