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.

  • 相关阅读:
    AVR单片机教程——EasyElectronics Library v1.1手册
    C++ lambda的演化
    希尔排序的正确性 (Correctness of ShellSort)
    PAT甲级满分有感
    PAT甲级题分类汇编——杂项
    Python第八章-异常
    Python第七章-面向对象高级
    Python第七章-面向对象初级
    Python第六章-函数06-高阶函数
    Python第六章-函数05-迭代器&生成器
  • 原文地址:https://www.cnblogs.com/a14907/p/5099445.html
Copyright © 2011-2022 走看看