zoukankan      html  css  js  c++  java
  • webapi中的自定义路由约束

    Custom Route Constraints

    You can create custom route constraints by implementing the IHttpRouteConstraint interface. For example, the following constraint restricts a parameter to a non-zero integer value.

    
    public class NonZeroConstraint : IHttpRouteConstraint
    {
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, 
            IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            object value;
            if (values.TryGetValue(parameterName, out value) && value != null)
            {
                long longValue;
                if (value is long)
                {
                    longValue = (long)value;
                    return longValue != 0;
                }
    
                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
                if (Int64.TryParse(valueString, NumberStyles.Integer, 
                    CultureInfo.InvariantCulture, out longValue))
                {
                    return longValue != 0;
                }
            }
            return false;
        }
    }
    

    The following code shows how to register the constraint:

    
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var constraintResolver = new DefaultInlineConstraintResolver();
            constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
    
            config.MapHttpAttributeRoutes(constraintResolver);
        }
    }

    Now you can apply the constraint in your routes:

    
    [Route("{id:nonzero}")]
    public HttpResponseMessage GetNonZero(int id) { ... }

    You can also replace the entire DefaultInlineConstraintResolver class by implementing the IInlineConstraintResolver interface. Doing so will replace all of the built-in constraints, unless your implementation of IInlineConstraintResolver specifically adds them.

  • 相关阅读:
    多项式多点求值和插值
    Java Dao设计模式
    (转)HTTP长连接和短连接
    JavaScript——this关键字
    JavaScript——Prototype详探
    JavaScript——特殊点总结
    JavaScript——正则表达式
    JavaScript——Window对象
    JavaScript——this、constructor、prototype
    JavaScript——事件模型
  • 原文地址:https://www.cnblogs.com/a14907/p/5099445.html
Copyright © 2011-2022 走看看