Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

asp.net mvc Question Routing

If you review a SO question URL you will see that an ID and a "SLUG" are passed to the Questions controller: https://stackoverflow.com/questions/676934/what-do-you-need-to-write-your-own-blog-engine. What I find interesting is you can change the "SLUG" portion of the URL without affecting the application's ability to route the request example. The only way I could think to pull this off is have a route that accepted an id and a "SLUG" and used a route constraint on the slug to ensure it followed a pattern. I had to use a constraint to ensure that having the two variables didn't result in this route matching all requests. Does anyone have a better way to accomplish this, or any examples of more advanced routing scenarios?

ADDITION:

I realize the SLUG is for human readablity, and I would like to duplicate this feature in another application. What is the best way to accomplish this.

Route:

routes.MapRoute(
    "Id + Slug",          // Route name
    "Test/{id}/{slug}",   // URL with parameters
    new                   // Parameter defaults
    {
        controller = "Test", 
        action = "Details", 
        id = "", 
        slug = "" 
    },  
    new { slug = new SlugConstraint() }
);

Simple Constraint:

public class SlugConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext,
        Route route,
        string parameterName,
        RouteValueDictionary values,
        RouteDirection routeDirection)
    {
        string value = values[parameterName].ToString();

        return value.Contains("-");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need to use the slug at all. It's probably just there for human readability and search engine optimization. You can ignore it when routing and just work up to the ID.

For instance, click here:

Stack Overflow Question Routing


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...