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)}]
下面定义了默认支持的约束:
| Constraint | Description | Example |
|---|---|---|
| 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.");
}
}
}
应用场景可以自己定义。
MVC 5 属性路由中添加自己的自定义约束的更多相关文章
- 【翻译】ASP.NET MVC 5属性路由(转)
转载链接:http://www.cnblogs.com/thestartdream/p/4246533.html 原文链接:http://blogs.msdn.com/b/webdev/archive ...
- vue 路由meta作用及在路由中添加props作用
vue路由meta:有利于我们处理seo的东西,我们在html中加入meta标签,就是有利于处理seo的东西,搜索引擎 在路由中传参是通过/:id传参代码如下: import Login from ' ...
- TWaver初学实战——如何在TWaver属性表中添加日历控件?
在日期输入框中添加日历控件,是一种非常流行和实用的做法.临渊羡鱼不如退而写代码,今天就看看在TWaver中是如何实现的. 资源准备 TWaver的在线使用文档中,就有TWaver Proper ...
- HTML 全局属性 = HTML5 中添加的属性。
属性 描述 accesskey 规定激活元素的快捷键. class 规定元素的一个或多个类名(引用样式表中的类). contenteditable 规定元素内容是否可编辑. contextmenu 规 ...
- [Asp.net MVC]Asp.net MVC5系列——在模型中添加验证规则
目录 概述 在模型中添加验证规则 自定义验证规则 伙伴类的使用 总结 系列文章 [Asp.net MVC]Asp.net MVC5系列——第一个项目 [Asp.net MVC]Asp.net MVC5 ...
- Web API中的路由(二)——属性路由
一.属性路由的概念 路由让webapi将一个uri匹配到对应的action,Web API 2支持一种新类型的路由:属性路由.顾名思义,属性路由使用属性来定义路由.通过属性路由,我们可以更好地控制We ...
- Asp.net MVC]Asp.net MVC5系列——在模型中添加
目录 概述 在模型中添加验证规则 自定义验证规则 伙伴类的使用 总结 系列文章 [Asp.net MVC]Asp.net MVC5系列——第一个项目 [Asp.net MVC]Asp.net MVC5 ...
- 第二十一节:Asp.Net Core MVC和WebApi路由规则的总结和对比
一. Core Mvc 1.传统路由 Core MVC中,默认会在 Startup类→Configure方法→UseMvc方法中,会有默认路由:routes.MapRoute("defaul ...
- MVC 支持同名路由,不同命名空间
有时候我们会碰到两个项目合在一起,那么必然会碰到两个同名的controller,其实MVC在注册路由,添加Route的时候可以指定当前规则解析那个命名空间下的所有Controller. 注:Contr ...
随机推荐
- 长轮询实现Chat并迁移到Azure测试
长轮询实现Chat并迁移到Azure测试 公司的OA从零开始进行开发,继简单的单点登陆.角色与权限.消息中间件之后,轮到在线即时通信的模块需要我独立去完成.这三周除了逛网店见爱*看动漫接兼职,基本上都 ...
- openssh6.7.deb download packed for debian7/ubuntu12.04 amd64
openssh the openssh-server on debian7/ubuntu12.04 is too old and out of date. so now we replace and ...
- [置顶] javascript-基于对象or面向对象?
最近完成了javascript的初级学习,在这个学习的视频中,我特别注意了两个词,解释性语言和对象,javascript按照我的理解,应该是种解释性语言,他有关于面向对象的思想的体现,但是,他和vb一 ...
- 解决gsoap中文乱码的问题
解决方法一: 在main函数里初始化soap结构体后加入 soap_set_mode(&soap,SOAP_C_UTFSTRING); 这样所有的C都是utf-8的格式,只要你的win ...
- Windows平台下安装Eclipse插件,开发Hadoop应用
欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...
- [jQuery]on和bind事件绑定的区别
on和bind事件绑定的区别 一个demo展示 <!DOCTYPE html> <html lang="zh"> <head> <titl ...
- oracle数据库一些用户管理语句
查询所有数据库用户 select * from dba_users 查看数据库名称 select name from v$database 查看权限 select * from user_sys_pr ...
- JavaEE XML XSL转换(XSLT)
XSL转换(XSLT) @author ixenos 定义: XSL转换机制可以指定将XML文档转换为其他格式的规则,例如,txt纯文本.XHTML或其他任何XML格式. 用途: XSLT通常用来将某 ...
- U31网管配置
1.新建网元和子架配置: 在拓扑图空白处新建对象-创建承载传输网元-选择设备-填写网元名称(A).网元类型.IP(查询出SNP的),网关IP会自动在此基础上加2.如果数据库为空先选离线- 机架子架配置 ...
- HDU------checksum
Quicksum Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Subm ...