开发者

Two different generic route types

开发者 https://www.devze.com 2022-12-18 13:25 出处:网络
I\'ve got two (so far) different types of routes in my ASP.NET MVC app, one is: {controller}/{action}/{id} and the other {controller}/{action}/{title}

I've got two (so far) different types of routes in my ASP.NET MVC app, one is: {controller}/{action}/{id} and the other {controller}/{action}/{title}

Currently I need to define the routes like this:

        routes.MapRoute (
            "Default_Title_Slug",                                       // Route name
            "product/details/{title}",                          // URL with parameters
            new { controller = "product", action = "details", title = "" }      // Parameter defaults
        );

        routes.MapRoute (
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "site", action = "index", id = "" }  // Parameter defaults
        );

Notice that the first one I've had to tie down to the product controller, this seems to be the only way I can get it work...otherwise the other routes end up looking like this:

/controller/action?id=number

Now I need to add another MapRoute ca开发者_开发技巧ll targeting another controller with the {title} segment...I don't want to create a new route for each specific entry I come up with in the future...is there a generic route I can create to map the /controller/action/title that'll play nicely with the /controller/action/id route?

Thanks,

Kieron


You can do that with a route-constraint, such as regex - a very similar example is here. Something like:

routes.MapRoute (
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "site", action = "index", id = "" },
    new { id = @"\d+" }
);
routes.MapRoute (
    "Default_Title_Slug",
    "{controller}/{action}/{title}",
    new { controller = "product", action = "details", title = "" }
);
0

精彩评论

暂无评论...
验证码 换一张
取 消