[英]Correct mapping correct route to action with similar url
我有两个必填路径:
1:本地主机:1207 /博客/ 2014/12 /文章名称
2:本地主机:1207 /博客/ 2014/12
现在,我为每条路线写了自定义映射
1:
routes.MapRoute(
name: "BlogArticle",
url: "blog/{year}/{month}/{title}",
defaults: new
{
controller = "Blog",
action = "Detail",
year = UrlParameter.Optional,
month = UrlParameter.Optional,
title = UrlParameter.Optional
}
);
2:
routes.MapRoute(
name: "BlogMonthList",
url: "blog/{year}/{month}",
defaults: new
{
controller = "Blog",
action = "MonthList",
year = UrlParameter.Optional,
month = UrlParameter.Optional
});
第二个不起作用,我不确定为什么。 作为答案的一部分,您能否解释一下原因?
我的解决方案必须使用RouteConfig.cs
我的控制器示例:
public BlogController : Controller{
public ActionResult MonthList(int year, int month)
{
var model = new MonthArticlesModel()
{
Year = year,
Month = month
};
return View(model);
}
public ActionResult Detail(int year, int month, string title)
{
var model = new DetailModel();
return View(model);
}
}
问题在于,没有办法区分路由,因为您已将所有参数都设置为可选参数,并且/Blog/2014/12/Article-Name
和/Blog/2014/12
与第一个路由匹配。
我建议您遵循更常规的路线,但是可以通过将路线指定为
routes.MapRoute(
name: "BlogMonthList",
url: "blog/{year}/{month}",
defaults: new { controller = "Blog", action = "MonthList" }
);
routes.MapRoute(
name: "BlogArticle",
url: "blog/{year}/{month}/{title}",
defaults: new { controller = "Blog", action = "Detail" }
);
然后/Blog/2014/12/Article-Name
将跳过第一条路线(仅接受2个参数),并重定向到Detail(int year, int month, string title)
但/Blog/2014/12
将匹配第一条路线,重定向到MonthList(int year, int month)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.