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
alphaMatches uppercase or lowercase Latin alphabet characters (a-z, A-Z){x:alpha}
boolMatches a Boolean value.{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value.{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(6)}
{x:length(1,20)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}
rangeMatches an integer within a range of values.{x:range(10,50)}
regexMatches 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.");
        }
    }
}

 


应用场景可以自己定义。

转载于:https://www.cnblogs.com/sgciviolence/p/5652772.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值