• MVC 5 属性路由中添加自己的自定义约束


    介绍约束

    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/整数', 并且id>=1,id<=20

    [Route("temp/{id:int:max(20):min(1)}]
     下面定义了默认支持的约束:
    ConstraintDescriptionExample
    alpha Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) {x:alpha}
    bool Matches a Boolean value. {x:bool}
    datetime Matches a DateTime value. {x:datetime}
    decimal Matches a decimal value. {x:decimal}
    double Matches a 64-bit floating-point value. {x:double}
    float Matches a 32-bit floating-point value. {x:float}
    guid Matches a GUID value. {x:guid}
    int Matches a 32-bit integer value. {x:int}
    length Matches a string with the specified length or within a specified range of lengths. {x:length(6)}
    {x:length(1,20)}
    long Matches a 64-bit integer value. {x:long}
    max Matches an integer with a maximum value. {x:max(10)}
    maxlength Matches a string with a maximum length. {x:maxlength(10)}
    min Matches an integer with a minimum value. {x:min(10)}
    minlength Matches a string with a minimum length. {x:minlength(10)}
    range Matches an integer within a range of values. {x:range(10,50)}
    regex Matches a regular expression. {x:regex(^d{3}-d{3}-d{4}$)}

    自定义路由约束

    约束实现

    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

    这里还有另外一种方式:https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

     不用使用 attribute方式:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
     
        var constraintsResolver = new DefaultInlineConstraintResolver();
     
        constraintsResolver.ConstraintMap.Add(“locale”, typeof(LocaleRouteConstraint));
     
        routes.MapMvcAttributeRoutes(constraintsResolver);
    }
    

     controller代码是这样的

    using System.Web.Mvc;
    namespace StarDotOne.Controllers
    {
        [Route("hello/{locale:locale(FR-FR)}/{action=Index}")]
        public class FRFRHomeController : Controller
        {
            // GET: /hello/fr-fr/
            public ActionResult Index()
            {
                return Content("Je suis le contrôleur FR-FR.");
            }
        }
    }
    


    应用场景可以自己定义。

  • 相关阅读:
    点击事件
    php if语句判定my查询是否为空
    php if语句判定ms查询是否为空
    thinkphp 原生sql使用分页类
    从JAVA客户端访问Redis示例(入门)
    Log4j日志级别
    网页正文抽取(包含提取图片)
    网络爬虫基本原理
    Java中替换HTML标签的方法代码
    Java/Js下使用正则表达式匹配嵌套Html标签
  • 原文地址:https://www.cnblogs.com/sgciviolence/p/5652772.html
Copyright © 2020-2023  润新知