asp.net-core 路由约束
示例
可以创建自定义路由约束,该约束可在路由内部使用以将参数约束为特定值或模式。
此约束将匹配典型的文化/地区模式,例如en-US,de-DE,zh-CHT,zh-Hant。
public class LocaleConstraint : IRouteConstraint { private static readonly Regex LocalePattern = new Regex(@"^[a-z]{2}(-[a-z]{2,4})?$", RegexOptions.Compiled| RegexOptions.IgnoreCase); public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (!values.ContainsKey(routeKey)) return false; string locale = values[routeKey] as string; if (string.IsNullOrWhiteSpace(locale)) return false; return LocalePattern.IsMatch(locale); } }
之后,必须先注册约束,然后才能在路由中使用约束。
services.Configure<RouteOptions>(options => { options.ConstraintMap.Add("locale", typeof(LocaleConstraint)); });
现在,它可以在路线内使用。
在控制器上使用
[Route("api/{culture:locale}/[controller]")] public class ProductController : Controller { }
在动作上使用它
[HttpGet("api/{culture:locale}/[controller]/{productId}"] public Task<IActionResult> GetProductAsync(string productId) { }
在默认路由中使用它
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "api/{culture:locale}/{controller}/{id?}"); routes.MapRoute( name: "default", template: "api/{controller}/{id?}"); });