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

后端 未结 6 1884
太阳男子
太阳男子 2020-12-01 07:46

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}

6条回答
  •  萌比男神i
    2020-12-01 08:05

    +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;
            }
        }
    

提交回复
热议问题