C# asp.net mvc路由问题

C# asp.net mvc路由问题,c#,.net,asp.net-mvc,asp.net-mvc-routing,C#,.net,Asp.net Mvc,Asp.net Mvc Routing,我已将此路由添加到我的全局asax中 routes.MapRoute( "News", // Route name "News/{timePeriod}/{categoryName}/{page}", // URL with parameters new { controller = "News", action = "Index", timePeriod = TimePeriod.AllTime, categoryName = "All", page

我已将此路由添加到我的全局asax中

routes.MapRoute(
    "News", // Route name
    "News/{timePeriod}/{categoryName}/{page}", // URL with parameters
    new { controller = "News", action = "Index", 
        timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
    new { page = @"^\d{1,3}$" }// Parameter defaults
);

routes.MapRoute(
    "News2", // Route name
    "News/{categoryName}/{page}", // URL with parameters
    new { controller = "News", action = "Index", 
        timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
    new { page = @"^\d{1,3}$" }// Parameter defaults
);
问题是像/News/add这样的URL不起作用(除非我添加了特定的路由)
有没有更好的方法不必在全局asax中指定url操作?

我想,这会抓住它。但前提是,如果您不传递任何像id这样的额外参数(因为,它非常类似于News2路由)

此外,请尝试路由调试器以测试所需的效果:

您上面的两条路由将分别发送到新闻控制器并点击“索引”操作。如果索引操作没有重载,而该重载将采用您指定的参数,则路由将无法正常工作。例如,您应该执行以下两个操作:

public ActionResult Index(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Index(string categoryName, int page) {..}
此外,您应该从第二条路由中删除默认的TimePeriod参数,因为您没有在路由本身中使用它:

routes.MapRoute(
                "News2", // Route name
                "News/{categoryName}/{page}", // URL with parameters
                new { controller = "News", action = "Index", categoryName = "All", page = 1 },
                new { page = @"^\d{1,3}$" }// Parameter defaults
            );
我建议为每个类别创建一个操作,而不是为每个类别创建一个路由。您可以将路线简化为:

routes.MapRoute(
                "News", // Route name
                "News/{action}/{timePeriod}/{page}", // URL with parameters
                new { controller = "News", action = "Index", timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
                new { page = @"^\d{1,3}$" }// Parameter defaults
            );
然后对每个类别进行操作:

public ActionResult All(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Sports(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Weather(TimePeriod timePeriod, string categoryName, int page) {..}

这样,您只需要一条路由。

顺便说一句,您标记为参数默认值的行是参数约束。参数默认值高一行。这是一个很好的解决方案,但也许reklas希望有不同的路由,以使他的URL更好。例如,当他显示结果时,他不需要添加新闻操作的页面,但需要它。@kMike-如果是这种情况,他只需要在路由中选择这些参数,他的url不必包含它们。
public ActionResult All(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Sports(TimePeriod timePeriod, string categoryName, int page) {..}

public ActionResult Weather(TimePeriod timePeriod, string categoryName, int page) {..}