I'm looking to set up simple routes so that {controller}/{id} would default to {controller}/details/{id}. I've set it up like in this post: ASP.NET MVC 4 Routes - controller/id vs controller/action/id
But that post suggests for the routes to work I would need int
{id} values. We use Guid ids.
Here is what I have:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute
(
name: "Detail",
url: "{controller}/{id}",
defaults: new { action = "Details", id = UrlParameter.Optional }
);
routes.MapRoute
(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Submission", action = "Index", id = UrlParameter.Optional }
);
}
}
Can I do this with Guid
ids?
The problem with your current route definition is, It will work for your particular request, but will break the existing default routing.When you try to access Home/About
, it will send you to the Details action of Home!.
To solve this,what you can do is to pass a route constraint where you can pass the regex for Guid
.
This should work fine.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute
(
name: "Detail",
url: "{controller}/{id}",
defaults: new { action = "Details", id = UrlParameter.Optional },
constraints: new { id = "[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
And change your action method parameter type to Guid
.
public class ProjectController : Controller
{
public ActionResult Details(Guid id)
{
return View();
}
}
For the request yourSite/project/someValidGuid
, now it will send the request to the Details
action on ProjectController
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments