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

后端 未结 6 1881
太阳男子
太阳男子 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条回答
  •  既然无缘
    2020-12-01 07:58

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

提交回复
热议问题