約束的作用是 只有大寫的參數(shù)值才能通過
?
一、定義約束
二、加載的時(shí)候引入約束
三、在controller 引入約束
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; using System.Web.Http.Routing; namespace WebApi { public class UpperCaseRouteConstraint : IHttpRouteConstraint { bool IHttpRouteConstraint.Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) { // parameterName的意思是約束的參數(shù)名稱 這里是 invalue // values 集合 包含參數(shù)名稱,比如 invalue 的值。 object casevalue; if(values.TryGetValue(parameterName, out casevalue))// 這里獲取 invalue 的值 { return casevalue.ToString().ToUpper() == casevalue.ToString(); } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Http.Routing; namespace WebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes DefaultInlineConstraintResolver constraintResolver = new DefaultInlineConstraintResolver(); constraintResolver.ConstraintMap.Add("UpperCase", typeof(UpperCaseRouteConstraint)); config.MapHttpAttributeRoutes(constraintResolver); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Web.Http; using WebApi.Properties; namespace WebApi.Controllers { public class ResourcesController : ApiController { [HttpGet] [Route("api/constrant/{invalue:UpperCase=TTT}")] public string GetValue(string invalue) { return invalue; } } }
?
?獲得定義一個(gè)新的 約束解析類
?
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http.Routing; namespace WebApi { public class ExtendDefaultInlineConstraintResolver: DefaultInlineConstraintResolver { public ExtendDefaultInlineConstraintResolver() { this.ConstraintMap.Add("UpperCase", typeof(UpperCaseRouteConstraint)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Http.Routing; namespace WebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes //DefaultInlineConstraintResolver constraintResolver = new DefaultInlineConstraintResolver(); //constraintResolver.ConstraintMap.Add("UpperCase", typeof(UpperCaseRouteConstraint)); ExtendDefaultInlineConstraintResolver constraintResolver = new ExtendDefaultInlineConstraintResolver(); config.MapHttpAttributeRoutes(constraintResolver); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
?
本文摘自 :https://www.cnblogs.com/