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 ...
随机推荐
- FastDFS接口API文档说明
FastDFS接口API文档说明 时间:2012-03-17 来源:R9IT 作者:R9传奇 一.命令行的上传: 上传命令1. /usr/local/bin/fdfs_upload_file conf ...
- JForum2.1.9 安装过程
JForum2.1.9 安装过程 JForum2.1.9 安装过程 2013/08/10 0:48 1.第一次接触 2013/08/08 在开源中国看到一个国外开源的Java论坛,然后下载JForum ...
- 一步步学习Python-django开发-添加后台管理
Pyhon-djano提供了一个很强大的后台管理功能,你很轻松的就可以拥有一个后台管理平台.你需要做啥呢?你只需要将需要管理员进行管理的表注册到管理site中即可: from django.contr ...
- python cookbook学习笔记 第一章 文本(1)
1.1每次处理一个字符(即每次处理一个字符的方式处理字符串) print list('theString') #方法一,转列表 结果:['t', 'h', 'e', 'S', 't', 'r', 'i ...
- MS Sql Server 消除重复行 保留信息完整的一条 2011-11-26 13:19(QQ空间)
select company ,count(company) as coun into myls from mylist group by company having count(company)& ...
- linux命令——iotop
查看CPU使用情况用top,查看I/O使用情况就需要iotop.这个命令是在 kernel v2.6.20中添加,安装的时候要注意内核的版本号. iotop常用快捷键 1. 左右箭头 --> 改 ...
- 关于ActiveMQ的一点总结
ActiveMQ入门 作者:一路向北 摘要:本文主要讲述ActiveMQ的基本知识和使用方法,并简单结合spring使用ActiveMQ. 一.ActiveMQ特性和使用总览 企业消息软件从80年代起 ...
- JS,CSS是前端,JAVA PHP ASP是后端,数据库是后端的处理对象,非代表前后底
大海-mysql-oracle(529513481) 19:02:18 象我这边,前台都是php,而php做数据分析是不太理想的,做中间件没人力,难办 横瓜(601069289) 19:20:15 ...
- jdk各版本新特性
只收纳常用的新特性 jdk1.4 1.引入断言 jdk5 1.引入泛型 2.引入枚举Enum 3.可以自动拆装箱 4.引入注解Annotation 5.引入新的迭代方式foreach 6.引入静态导入 ...
- [ios2]警告:Block的Retain Cycle的解决方法 【转】
<span style="background-color: rgb(248, 248, 248); font-family: 'PT Sans', Geogia, Baskervil ...