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.

  • 相关阅读:
    JPA注解 @DiscriminatorValue 使用
    随笔
    Win10 启用 FTP
    Java后端模拟前端请求
    ueditor上传路径改成绝对路径
    CSS Web Fonts 网络字体
    调试:'Object reference note set to an instance of an object.'
    类转json、 json转xml的方法,转SortedDictionary转 xml 的方法。
    xml的问题 XmlDocument 与json转换
    websocket
  • 原文地址:https://www.cnblogs.com/a14907/p/5099445.html
Copyright © 2011-2022 走看看