ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+

前端 未结 6 1317
孤街浪徒
孤街浪徒 2020-11-29 12:00

I\'m trying to write a route with a nullable int in it. It should be possible to go to both /profile/ but also /profile/\\d+.

route         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 12:42

    I needed to validate a few things with more than just a RegEx but was still getting an issue similar to this. My approach was to write a constraint wrapper for any custom route constraints I may already have:

    public class OptionalRouteConstraint : IRouteConstraint
    {
        public IRouteConstraint Constraint { get; set; }
    
        public bool Match
            (
                HttpContextBase httpContext,
                Route route,
                string parameterName,
                RouteValueDictionary values,
                RouteDirection routeDirection
            )
        {
            var value = values[parameterName];
    
            if (value != UrlParameter.Optional)
            {
                return Constraint.Match(httpContext, route, parameterName, values, routeDirection);
            }
            else
            {
                return true;
            }
        }
    }
    

    And then, in constraints under a route in RouteConfig.cs, it would look like this:

    defaults: new {
        //... other params
        userid = UrlParameter.Optional
    }
    constraints: new
    {
        //... other constraints
        userid = new OptionalRouteConstraint { Constraint = new UserIdConstraint() }
    }
    

提交回复
热议问题