Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

asp.net mvc - How can I create a route constraint of type System.Guid?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...