Search code examples
asp.net-mvcasp.net-mvc-2asp.net-mvc-routingurl-routing

IRouteConstraint for enum


I want to create an IRouteConstraint that filters a value against possible values of an enum. I tried to google it for myself, but that didn't result in anything.

Any ideas?


Solution

  • See this

    Essentially, you need

      private Type enumType;
    
      public EnumConstraint(Type enumType)
      {
        this.enumType = enumType;
      }
    
      public bool Match(HttpContextBase httpContext, 
        Route route, 
        string parameterName,     
        RouteValueDictionary values, 
        RouteDirection routeDirection)
      {
        // You can also try Enum.IsDefined, but docs say nothing as to
        // is it case sensitive or not.
        return Enum.GetNames(enumType).Any(s => s.ToLowerInvariant() == values[parameterName].ToString());
      }