views:

134

answers:

2

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?

Thanks

+5  A: 

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() });
kazimanzurrashid
just add a "if (values[parameterName] is Guid) return true;" to catch strongly typed parameters, as for example from tests and for outbound routing ;)
Nikos D
+2  A: 

+1 @kazimanzurrashid. Seems spot on.

I'll give an alternative for those who haven't got C#4.0, of which Guid.TryParse is part of. There's another alternative with Regex but probably not worth the bother.

 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))
                {
                    //replace with Guid.TryParse when available.
                    try
                    {
                        Guid guid = new Guid(stringValue);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }


                }
            }

            return false;
        }
    }
dove