Default mvc 5 route with guid id
-
21-12-2019 - |
Question
I'm trying to setup an mvc 5 attrribute route so that
https://localhost/19a6de7e-ee19-43f5-a9c9-8bbdc8dcfc5e
routes to /home/index initializing the id param and I cant seem to get it quite right.
I have added routes.MapMvcAttributeRoutes(); to my register routes after the default mapped route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I have tried a number of things but cant seem to get it to work unless the route is fully defined.
Any advice?
public class HomeController : Controller
{
[Route("{id?}")]
public ActionResult Index(Guid? id)
{
ViewBag.Message = id;
return View();
}
}
Solution
There is now an in-built GuidRouteConstraint() added that would be preferable to using a RegEx.
OTHER TIPS
@chrisp_68, you will need a custom route placed before the Default route:
routes.MapRoute(
name: "Just ID",
url: "{id}",
defaults: new { controller = "Home", action = "Index" }
);
Then, you need to create an action that takes id as a parameter:
public ActionResult IndexID(string id) {
...
}
Another thing you may consider is constraining the value of id to a guid pattern:
constraints: new { id = @"[a-f0-9-]+" }
(Or whatever pattern you need)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow