繁体   English   中英

ASP.NET MVC路由问题

[英]asp.net mvc routing issues

我已经将此路由添加到我的全局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路由非常相似)。

routes.MapRoute(
"News0",
"News/{action}",
new { controller = "News", action = "Index" }
);

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

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

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) {..}

这样,您所需要做的就是一条路线。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM