Can anyone point me in the right direction on how to map a route which requires two guids?
ie. http://blah.com/somecontroller/someaction/{firstGuid}/{secondGuid}
where both firstGuid and secondGuid are not optional and must be of type system.Guid?
Routing constraints lets you restrict how the parameters in the route template are matched. It helps to filter out the input parameter and action method can accept. Routing constraints let you restrict how the parameters in the route template are matched.
We can also define parameter constraints by placing a constraint name after the parameter name separated by a colon. There are many builtin routing constraints available. We can also create custom routing constraints. To create a custom route constraint, we have implemented our class from an IRouteConstraint interface.
Implement the IRouteConstraint Match method in ASP.NET Core To create a custom route constraint, you should create a class that extends the IRouteConstraint interface and implements its Match method.
We can apply the multiple constraints to a parameter by a colon (:) separator. [Route(URLPath/{parameterName: constrain:Constrain:….})] In the preceding example, the route will only be selected if the parameter id is an integer as well as a value of id greater than 1000.
Create a RouteConstraint like the following:
public class GuidConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (values.ContainsKey(parameterName)) { string stringValue = values[parameterName] as string; if (!string.IsNullOrEmpty(stringValue)) { Guid guidValue; return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty); } } return false; }}
Next when adding the route :
routes.MapRoute("doubleGuid", "{controller}/{action}/{guid1}/{guid2}", new { controller = "YourController", action = "YourAction" }, new { guid1 = new GuidConstraint(), guid2 = new GuidConstraint() });
For MVC 5 there is already implemented the GuidRouteConstraint Class:
https://msdn.microsoft.com/en-us/library/system.web.mvc.routing.constraints.guidrouteconstraint(v=vs.118).aspx
Full list of available MVC constraints:
https://msdn.microsoft.com/en-us/library/system.web.mvc.routing.constraints(v=vs.118).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With