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 ...
随机推荐
- java读取properties 文件信息
src下config/tank.properties文件 initTankCount=10 ReinitTankCount=8 Etmspeed=15 Mtmspeed=15 MTankCount ...
- linux下安装java
搞了一年IT了,作为IT人没怎么玩过linux挺丢脸的,要好好整整. 先从熟悉的来,在linux下开发java,首先要搭建环境. linux有一个工具yum,非常好用. 1.yum install j ...
- zTree应用实例详讲
zTree应用实例详讲(1) 因为项目的需要,要创建一棵动态的文件树,此树除了实现异步获取子节点外,还要实现对树节点的增.删.改.查.移动.重命名.批量删除.批量移动. 每一个操作都要和数据库打交道. ...
- LNMP安装与配置
Nginx与apache.lighttp性能综合对比,如下图: 注意:关闭rpm默认安装的apache和mysql 1.准备php函数的rpm包 y ...
- 改ext界面
以前的ext界面 被我给换成了 为的是响应整个系统平台的颜色色调---绿色,还得科技搭配蓝色,我可是想破了脑袋,才想到这种蓝绿搭配,领导们不知道怎么想的
- phper談談最近重構代碼的感受(2)
重构代码更多的是对程序的可读性和可扩展性上做一些优化. 首先我对可读性进行细化.借鉴大神川山甲的重构系列文http://www.cnblogs.com/baochuan/archive/2012/03 ...
- Hadoop完全分布式搭建过程中遇到的问题小结
前一段时间,终于抽出了点时间,在自己本地机器上尝试搭建完全分布式Hadoop集群环境,也是借助网络上虾皮的Hadoop开发指南系列书籍一步步搭建起来的,在这里仅代表hadoop初学者向虾皮表示衷心的感 ...
- js动画(二)
嗯,今天好冷,特别冷,我的手指,都冻的打不了字了.今天一件特别的傻的事就是,在 for(var i;i<obj.length;i++){} 找了半天没有注意到 var i 没有赋值.够150 了 ...
- Java深入研究【1、object类】
一.概述Object类是所有Java类的祖先.每个类都使用 Object 作为超类.所有对象(包括数组)都实现这个类的方法. 参考英文:* Class {@code Object} is the ro ...
- MVC源码解析 - 配置注册 / 动态注册 HttpModule
本来这一篇, 是要继续 Pipeline 的, 但是在 Pipeline之前, 我看到了InitModules()方法, 所以决定, 在中间穿插一篇进来. 这一篇来讲一下 IHttpModule 的加 ...