【发布时间】:2011-09-27 02:48:06
【问题描述】:
在 ASP.NET MVC(3 或 4DP)中使用开箱即用的方法定位器,有没有一种方法可以让 MVC 框架区分字符串和 Guid,而无需解析控制器操作中的参数?
URL 的使用示例
http://[domain]/customer/details/F325A917-04F4-4562-B104-AF193C41FA78
执行
public ActionResult Details(Guid guid)
方法和
执行
public ActionResult Details(string id)
方法。
不做任何改动,显然方法有歧义,如下:
public ActionResult Details(Guid id)
{
var model = Context.GetData(id);
return View(model);
}
public ActionResult Details(string id)
{
var model = Context.GetData(id);
return View(model);
}
导致错误:
The current request for action 'Details' on controller type 'DataController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Details(System.Guid) on type Example.Web.Controllers.DataController
System.Web.Mvc.ActionResult Details(System.String) on type Example.Web.Controllers.DataController
我尝试使用自定义约束(基于How can I create a route constraint of type System.Guid?)尝试通过路由将其推送:
routes.MapRoute(
"Guid",
"{controller}/{action}/{guid}",
new { controller = "Home", action = "Index" },
new { guid = new GuidConstraint() }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
并将动作签名切换为:
public ActionResult Details(Guid guid)
{
var model = Context.GetData(guid);
return View(model);
}
public ActionResult Details(string id)
{
var model = Context.GetData(id);
return View(model);
}
约束执行并通过,因此参数被发送到一个动作,但看起来仍然是一个字符串,因此对于两个方法签名来说是模棱两可的。我预计操作方法的定位方式会导致歧义,因此可以通过插入自定义模块来定位方法来覆盖。
同样的结果可以通过解析字符串参数来实现,但为了简洁起见,避免在操作中出现这种逻辑(更不用说希望以后重用)。
【问题讨论】:
-
你说得对,动作方法定位器忽略了路由约束。如果删除字符串操作方法,是否会选择 guid 操作方法?
-
MVC 不支持仅基于签名的方法重载 - 对您来说最简单的解决方案可能是简单地拥有两个唯一命名的操作方法,一个用于 GUID(详细信息)的详细信息,另一个用于获取详细信息按名称(可能是搜索还是信息?)。
-
@bzlm - 正确,删除字符串操作将选择 Guid(假设它通过约束或可以解析为 Guid)。
标签: asp.net-mvc asp.net-mvc-routing guid