码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-07-08 11:38:24      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

介绍约束

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


应用场景可以自己定义。

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

标签:

原文地址:http://www.cnblogs.com/sgciviolence/p/5652772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!