Using local method locators in ASP.NET MVC (3 or 4DP), there is a way for the MVC structure to distinguish between a string and a Guid without having to parse a parameter in a controller action
Usage examples will be for URL
http: // [domain] / customer / details / F325A917-04F4-4562-B104-AF193C41FA78
execute
public ActionResult Details(Guid guid)
and
http: // [domain] / customer / details / bill-gates
execute
public ActionResult Details(string id)
method.
Without changes, the methods are obviously ambiguous:
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); }
leads to an error:
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
I tried to use a custom constraint (based on How to create a route constraint of type System.Guid? ) To try to execute it through routing:
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 } );
And switched the action signatures to:
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); }
The restriction is fulfilled and passes, so the argument is sent to the action, but, apparently, still as a string and, therefore, ambiguous for the two method signatures. I expect that there is something about how the action methods are ambiguous, and therefore can be overridden by connecting a user module to search for methods.
The same result can be achieved by parsing a string parameter, but for brevity it would be very useful to avoid this logic in action (not to mention reusing it later).