• 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.

  • 相关阅读:
    深度图像的获取原理
    第二章 排序 || 第19节 最短子数组练习题
    第二章 排序 || 第18节 有序矩阵查找练习题
    tensorflow 之tf.nn.depthwise_conv2d and separable_conv2d实现及原理
    tensorflow 之常见模块conv,bn...实现
    机器学习中的训练数据不平衡问题
    一些智力题
    Pytoch 抽取中间层特征方法
    娱乐一下
    java访问ad域
  • 原文地址:https://www.cnblogs.com/a14907/p/5099445.html
Copyright © 2020-2023  润新知