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 ...
随机推荐
- jquery验证表单中的单选与多选
jquery验证表单中的单选与多选 这里所说的,用jquery去验证某一组多选至少要有一个选中,某一组单选至少有一个选中,,大家都知道单一的一个用js比较好验证,但是想要用jquery的验证并且用到j ...
- HTML5 Canvas中实现绘制一个像素宽的细线
正统的HTML5 Canvas中如下代码 ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(10, 100); ctx.lineTo(300,100); c ...
- jQuery Mobile (整合版)
jQuery Mobile (整合版) 前言 为了方便大家看的方便,我这里将这几天的东西整合一下发出. 里面的例子请使用手机浏览器查看. 什么是jQuery Mobile? jquery mobile ...
- 深入浅出Mybatis-sql自动生成
本文提供了一种自动生成sql语句的方法,它针对的对象是有主键或唯一索引的单表,提供的操作有增.删.改.查4种.理解本文和本文的提供的代码需要有java注解的知识,因为本文是基于注解生成sql的.本文适 ...
- php提供service总结---wsdl篇
越来越多的架构偏向于面向接口和面向服务的设计了,当我们把抽象的落地变为实际的时候,我们感觉到了代码的厚度.而当我们把具体的业务再进一步抽象,我们就能发现藏在细节深处的回馈. php可以提供servic ...
- Hexo+NextT基本设置【3】
该系列博客列表请访问:http://www.cnblogs.com/penglei-it/category/934299.html 摘要 或许在你看到我这篇我文章之前,你已经成功的通过Git ...
- [jstips]向数组中插入一个元素
向现有数组中插入一个元素是经常会见到的一个需求.你可以: 使用push将元素插入到数组的尾部: 使用unshift将元素插入到数组的头部: 使用splice将元素插入到数组的中间: 上面那些方法都是常 ...
- MySQL 性能优化神器 Explain 使用分析
简介 MySQL 提供了一个 EXPLAIN 命令, 它可以对 SELECT 语句进行分析, 并输出 SELECT 执行的详细信息, 以供开发人员针对性优化. EXPLAIN 命令用法十分简单, 在 ...
- codevs1993草地排水(最大流)
最近学了最大流,于是去codevs找了几道最大流裸题(这是我第一次写网络流). 题目大意:求一个图的最大流(就是这样的裸题) 第一次A网络流的题,发个博客纪念一下. var n,m,i,j,k,h,t ...
- 【USACO】滑雪课程
滑雪课程贝西去科罗拉多州去滑雪,不过还她不太会玩,只是个能力为 1 的渣渣.贝西从 0 时刻进入滑雪场,一到 T 时刻就必须离开.滑雪场里有 N 条斜坡,第 i 条斜坡滑行一次需要 Di 分钟,要求游 ...