maproute 方法 asp.net mvc 中基于约定的路由问题
Issue with convention-based Route in maproute method asp.net mvc
我有以下路线及其动作方法。
routes.MapRoute(
"Movies",
"Movies/{action}/{id}/{Genre}/{myprop}",
new { controller = "Movies", action = "Random", id=UrlParamter.Optional, Genre=UrlParameter.Optional,myprop = UrlParameter.Optional }
new { Genre=@"^[a-zA-Z]+$",myprop=@"\d{2}" }
);
public ActionResult Random(string id, string Genre, string myprop)
{
var movie = new Movie() { Name = "Shrek!" };
ViewBag.idgm = id + " " + Genre + " " + myprop;
return View(movie);
}
现在,当我尝试从中获取 URL 时:
http://localhost:60008/Movies/Random/5/qweqw
我得到一个 404。
但如果我尝试
http://localhost:60008/Movies/Random/5/qweqw/23
有效。我不明白为什么会这样。有人可以帮忙吗?
这是我完整的地图路线方法:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Movies",
"Movies/{action}/{id}/{genre}/{myprop}",
new { controller = "Movies", action = "Random", genre = UrlParameter.Optional, myprop = UrlParameter.Optional },
new { Genre= @"^[a-zA-Z]+$", myprop=@"\d{2}" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{myid}",
defaults: new { controller = "Home", action = "Index", myid = UrlParameter.Optional }
);
}
第一个 URL 收到 404 的原因是 myprop
的路由约束使得该参数 需要 - 它只匹配一个 2 位数字,从不匹配空字符串。
myprop=@"\d{2}"
要修复它,请更改正则表达式以匹配 2 位数字 或 空字符串。
myprop = @"\d{2}|^$"
说明
^$
将匹配零长度字符串。 |
是正则表达式更改字符(大致相当于逻辑或)。正则表达式必须允许空字符串通过,这样约束才能成功,然后才能分析值 UrlParameter.Optional
。实际上,不允许零长度字符串匹配参数是必需的,因为正则表达式失败首先发生。
我有以下路线及其动作方法。
routes.MapRoute(
"Movies",
"Movies/{action}/{id}/{Genre}/{myprop}",
new { controller = "Movies", action = "Random", id=UrlParamter.Optional, Genre=UrlParameter.Optional,myprop = UrlParameter.Optional }
new { Genre=@"^[a-zA-Z]+$",myprop=@"\d{2}" }
);
public ActionResult Random(string id, string Genre, string myprop)
{
var movie = new Movie() { Name = "Shrek!" };
ViewBag.idgm = id + " " + Genre + " " + myprop;
return View(movie);
}
现在,当我尝试从中获取 URL 时:
http://localhost:60008/Movies/Random/5/qweqw
我得到一个 404。
但如果我尝试
http://localhost:60008/Movies/Random/5/qweqw/23
有效。我不明白为什么会这样。有人可以帮忙吗?
这是我完整的地图路线方法:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Movies",
"Movies/{action}/{id}/{genre}/{myprop}",
new { controller = "Movies", action = "Random", genre = UrlParameter.Optional, myprop = UrlParameter.Optional },
new { Genre= @"^[a-zA-Z]+$", myprop=@"\d{2}" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{myid}",
defaults: new { controller = "Home", action = "Index", myid = UrlParameter.Optional }
);
}
第一个 URL 收到 404 的原因是 myprop
的路由约束使得该参数 需要 - 它只匹配一个 2 位数字,从不匹配空字符串。
myprop=@"\d{2}"
要修复它,请更改正则表达式以匹配 2 位数字 或 空字符串。
myprop = @"\d{2}|^$"
说明
^$
将匹配零长度字符串。 |
是正则表达式更改字符(大致相当于逻辑或)。正则表达式必须允许空字符串通过,这样约束才能成功,然后才能分析值 UrlParameter.Optional
。实际上,不允许零长度字符串匹配参数是必需的,因为正则表达式失败首先发生。