How can I create a route constraint of type System.Guid?

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() });

Leave a Comment