nat*_*ere 6 parameters asp.net-mvc null routing global-asax
我不知道为什么我的路线有冲突.我在我的Global.asax文件中有这些:
routes.MapRoute(
"CustomerView", "{controller}/{action}/{username}",
new { controller = "Home", action = "Index", username = "" }
);
routes.MapRoute(
"Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "0" }
);
Run Code Online (Sandbox Code Playgroud)
到目前为止,一切都运行良好,除非我创建一个控制器动作,如下所示:
public ActionResult MyAction(int id)
{
//Do stuff here
return View();
}
Run Code Online (Sandbox Code Playgroud)
当我尝试通过http:// mydomain/MyController/MyAction/5查看它时,我得到:
'/'应用程序中的服务器错误.
参数字典包含'InTouch.Controllers.OrderController'中方法'System.Web.Mvc.ActionResult Track(Int32)'的非可空类型'System.Int32'的参数'id'的空条目.要使参数可选,其类型应为引用类型或Nullable类型.参数名称:参数
告诉我,这个id价值没有得到正确的解读.当然enoguh,当我交换周围的路线顺序它工作正常.到目前为止,我的(理所当然有限的)理解是,如果路由中指定的变量名与控制器动作定义中指定的变量名匹配,则它将假定一个不管顺序.显然我错了.交换订单会导致其他控制器操作中断.在这种情况下,处理我的路线的正确方法是什么?
小智 13
你的例子的问题是匹配发生在第一条路线上,它看到"5"作为用户名参数.您可以使用约束来限制每个参数接受的值,以实现您想要的效果.由于接受Id的"默认"路由比"CustomerView"路由更具限制性,因此我首先列出"默认"路由,并对Id参数进行约束:
routes.MapRoute(
"Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "0" },
new { id = @"\d+" }
);
Run Code Online (Sandbox Code Playgroud)
如果Id是整数值,这将导致第一个路径仅匹配.然后,所有其他请求将进入"CustomerView"路由,该路由将获取没有整数作为第三个参数的任何其他请求.