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/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-08-11 05:43:24

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

【翻译】ASP.NET MVC 5属性路由

原文链接:http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#why-attribute-routing 最近在学习MVC相关的东西,今天刚好到msdn上看到了这样的一片文章,感觉不错,于是决定将它翻译出来和博友们一起分享下.我第一次发表文章,有不对的地方非常欢迎指出. —— 写在前面 废话不多说了,咱们开始吧 路由是ASP.NET MVC 怎样去用一个URI去匹配一个

向属性文件中添加属性

public static void main(String[] args) { saveProperties("aa","bb"); } public static void saveProperties(String key,String value){ Properties p = new Properties(); p.setProperty(key, value); try { FileOutputStream out = new FileOutputSt

[Asp.net MVC]Asp.net MVC5系列——在模型中添加验证规则

目录 概述 在模型中添加验证规则 自定义验证规则 伙伴类的使用 总结 系列文章 [Asp.net MVC]Asp.net MVC5系列——第一个项目 [Asp.net MVC]Asp.net MVC5系列——添加视图 [Asp.net MVC]Asp.net MVC5系列——添加模型 [Asp.net MVC]Asp.net MVC5系列——从控制器访问模型中的数据 [Asp.net MVC]Asp.net MVC5系列——添加数据 概述 上篇文章中介绍了添加数据,在提交表单的数据的时候,我们需

Asp.net MVC]Asp.net MVC5系列——在模型中添加

目录 概述 在模型中添加验证规则 自定义验证规则 伙伴类的使用 总结 系列文章 [Asp.net MVC]Asp.net MVC5系列--第一个项目 [Asp.net MVC]Asp.net MVC5系列--添加视图 [Asp.net MVC]Asp.net MVC5系列--添加模型 [Asp.net MVC]Asp.net MVC5系列--从控制器访问模型中的数据 [Asp.net MVC]Asp.net MVC5系列--添加数据 概述 上篇文章中介绍了添加数据,在提交表单的数据的时候,我们需

asp.net core 系列 6 路由(中)

一.URL 生成 接着上篇讲MVC的路由,MVC 应用程序可以使用路由的 URL 生成功能,生成指向操作的 URL 链接. 生成 URL 可消除硬编码 URL,使代码更稳定.更易维护. 此部分重点介绍 MVC 提供的 URL 生成功能,并且仅涵盖 URL 生成工作原理的基础知识. IUrlHelper 接口用于生成 URL,是 MVC 与路由之间的基础结构的基础部分. 在控制器.视图和视图组件中,可通过 Url 属性找到 IUrlHelper 的实例. // // mvc 框架的Controll

MVC 支持同名路由,不同命名空间

有时候我们会碰到两个项目合在一起,那么必然会碰到两个同名的controller,其实MVC在注册路由,添加Route的时候可以指定当前规则解析那个命名空间下的所有Controller. 注:Controller的调用是通过IControllerFactory,反射调用目标Controller,不指定目标命名空间,直接从BuildManager.GetReferencedAssemblies();如下. private static List<Type> controllerTypes = ne

drf框架中jwt认证,以及自定义jwt认证

0909自我总结 drf框架中jwt 一.模块的安装 官方:http://getblimp.github.io/django-rest-framework-jwt/ 他是个第三方的开源项目 安装:pip install djangorestframework-jwt 使用自带设定好的jwt from django.urls import path from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ path(

flask中的endpoint、自定义转化器、与djnago中session区别、利用装饰器实现登录认证

flask路由中的endpoint 与自定义转化器 ''' endpoint主要用于 反向解析, 例如:login函数中配的路由是/login,其中endpoint='lg' 则在其他函数,可以用 url=url_for('lg'),redirect(url)直接访问login函数 ''' ''' 自定义转化器,可以用来动态更新url_for 的跳转路由 其中 to_python主要是给后端的,可以对路由参数做修改 to_url是给前端url的,可以更新指定的url ''' flask与djan

Asp.Net Web API 2第八课——Web API 2中的属性路由

参考页面: http://www.yuanjiaocheng.net/webapi/web-api-gaisu.html http://www.yuanjiaocheng.net/webapi/create-web-api-proj.html http://www.yuanjiaocheng.net/webapi/test-webapi.html http://www.yuanjiaocheng.net/webapi/web-api-controller.html http://www.yuan