How to map a route for /News/5 to my news controller

自古美人都是妖i 提交于 2019-12-03 10:55:29
Nick Bork

Your {controller}/{id} route was correct but you problaby registered it AFTER the other route. In the route list it searches top down and the first match it finds wins.

To help steer routing I would suggest creating route constraints for this to ensure that #1 the controller exists and #2 the {id} is a number.

See this article

Mainly:

 routes.MapRoute( 
        "Index Action", // Route name 
        "{controller}/{id}", // URL with parameters EDIT: forgot starting "
        new { controller = "News", action = "Index" },
        new {id= @"\d+" }
    ); 

You need to make sure your new route is before your default route, like so:

    routes.MapRoute(
        "NewsAbbr", // Route name
        "{controller}/{id}", // URL with parameters
        new { controller = "News", action = "Index", id = -1 } // Parameter defaults
    );


    routes.MapRoute(
        "News", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "News", action = "Index", id = -1 } // Parameter defaults
    );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!