我的目标是我仍然想使用默认的asp.net mvc id
,但我想在这样的控制器中使用Guid
http://example.com/MyController/Index/387ecbbf-90e0-4b72-8768-52c583fc715b
这是我的路线
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
MyController现在
public ActionResult Index(Guid guid)
{
return View();
}
给我错误
参数字典包含参数'guid'的空条目 非可空类型'System.Guid'的方法 'System.Web.Mvc.ActionResult Index(System.Guid)'
我猜是因为我在路线上有身份证?如何在一个控制器中使用GUID作为参数,在应用程序的其余部分中使用id
(默认情况下)?
答案 0 :(得分:11)
只需将参数名称从guid
更改为id
:
public ActionResult Index(Guid id)
{
return View();
}
绑定动作时,ASP.NET MVC会检查动作方法的类型和名称,并将它们映射到请求提供的参数。由于路径中使用了术语id
,因此必须相应地命名操作的参数。