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

后端 未结 2 850
耶瑟儿~
耶瑟儿~ 2021-02-13 15:46

I am trying to identify how to map a route for /News/5 to my news controller.

This is my NewsController:

public class NewsController : BaseController
{
          


        
相关标签:
2条回答
  • 2021-02-13 15:53

    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
        );
    
    0 讨论(0)
  • 2021-02-13 15:56

    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+" }
        ); 
    
    0 讨论(0)
提交回复
热议问题