介绍约束
ASP.NET MVC和web api 同时支持简单和自定义约束,简单的约束看起来像:
routes.MapRoute("blog", "{year}/{month}/{day}", new { controller = "blog", action = "index" }, new { year = @"\d{4}", month = @"\d{2}", day = @"\d{2}" });
属性路由约束简单版
只匹配‘temp/selsius‘ 和‘temp/fahrenheit‘俩种情况
[Route("temp/{scale:values(celsius|fahrenheit)}")]
只匹配‘temp/整数‘
[Route("temp/{id:int}]
自定义路由约束
约束实现
public class LocaleRouteConstraint : IRouteConstraint { public string Locale { get; private set; } public LocaleRouteConstraint(string locale) { Locale = locale; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { object value; if (values.TryGetValue("locale", out value) && !string.IsNullOrWhiteSpace(value as string)) { string locale = value as string; if (isValid(locale)) { return string.Equals(Locale, locale, StringComparison.OrdinalIgnoreCase); } } return false; } private bool isValid(string locale) { string[] validOptions = "EN-US|EN-GB|FR-FR".Split(‘|‘) ; return validOptions.Contains(locale.ToUpper()); } }
增加自定义路由属性
public class LocaleRouteAttribute : RouteFactoryAttribute { public LocaleRouteAttribute(string template, string locale) : base(template) { Locale = locale; } public string Locale { get; private set; } public override RouteValueDictionary Constraints { get { var constraints = new RouteValueDictionary(); constraints.Add("locale", new LocaleRouteConstraint(Locale)); return constraints; } } public override RouteValueDictionary Defaults { get { var defaults = new RouteValueDictionary(); defaults.Add("locale", "en-us"); return defaults; } } }
MVC Controller 或 Action使用自定义的约束属性
using System.Web.Mvc; namespace StarDotOne.Controllers { [LocaleRoute("hello/{locale}/{action=Index}", "EN-GB")] public class ENGBHomeController : Controller { // GET: /hello/en-gb/ public ActionResult Index() { return Content("I am the EN-GB controller."); } } }
另一个controller
using System.Web.Mvc; namespace StarDotOne.Controllers { [LocaleRoute("hello/{locale}/{action=Index}", "FR-FR")] public class FRFRHomeController : Controller { // GET: /hello/fr-fr/ public ActionResult Index() { return Content("Je suis le contrôleur FR-FR."); } } }
‘/hello/en-gb‘ 将会匹配到ENGBHomeController
’/hello/fr-fr‘将会匹配到FRFRHomeController
应用场景可以自己定义。
时间: 2024-10-10 11:37:59