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.

  • 相关阅读:
    js判断是否是合法的端口号
    解决tomcat中文乱码
    使用java代码删除nexus maven仓库中的jar包、pom.xml等组件
    基于 Kubernetes 构建企业 Jenkins 持续集成平台
    minio部署
    elaticsearch 部署
    skywalking 8.0 配置文件
    使用node local dns来提升ClusterDNS服务质量
    kubernetes之监控Operator部署Prometheus
    夜莺监控+prometheus 架构图
  • 原文地址:https://www.cnblogs.com/a14907/p/5099445.html
Copyright © 2011-2022 走看看