介绍约束

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 属性路由中添加自己的自定义约束的更多相关文章

  1. 【翻译】ASP.NET MVC 5属性路由(转)

    转载链接:http://www.cnblogs.com/thestartdream/p/4246533.html 原文链接:http://blogs.msdn.com/b/webdev/archive ...

  2. vue 路由meta作用及在路由中添加props作用

    vue路由meta:有利于我们处理seo的东西,我们在html中加入meta标签,就是有利于处理seo的东西,搜索引擎 在路由中传参是通过/:id传参代码如下: import Login from ' ...

  3. TWaver初学实战——如何在TWaver属性表中添加日历控件?

    在日期输入框中添加日历控件,是一种非常流行和实用的做法.临渊羡鱼不如退而写代码,今天就看看在TWaver中是如何实现的.   资源准备   TWaver的在线使用文档中,就有TWaver Proper ...

  4. HTML 全局属性 = HTML5 中添加的属性。

    属性 描述 accesskey 规定激活元素的快捷键. class 规定元素的一个或多个类名(引用样式表中的类). contenteditable 规定元素内容是否可编辑. contextmenu 规 ...

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

    目录 概述 在模型中添加验证规则 自定义验证规则 伙伴类的使用 总结 系列文章 [Asp.net MVC]Asp.net MVC5系列——第一个项目 [Asp.net MVC]Asp.net MVC5 ...

  6. Web API中的路由(二)——属性路由

    一.属性路由的概念 路由让webapi将一个uri匹配到对应的action,Web API 2支持一种新类型的路由:属性路由.顾名思义,属性路由使用属性来定义路由.通过属性路由,我们可以更好地控制We ...

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

    目录 概述 在模型中添加验证规则 自定义验证规则 伙伴类的使用 总结 系列文章 [Asp.net MVC]Asp.net MVC5系列——第一个项目 [Asp.net MVC]Asp.net MVC5 ...

  8. 第二十一节:Asp.Net Core MVC和WebApi路由规则的总结和对比

    一. Core Mvc 1.传统路由 Core MVC中,默认会在 Startup类→Configure方法→UseMvc方法中,会有默认路由:routes.MapRoute("defaul ...

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

    有时候我们会碰到两个项目合在一起,那么必然会碰到两个同名的controller,其实MVC在注册路由,添加Route的时候可以指定当前规则解析那个命名空间下的所有Controller. 注:Contr ...

随机推荐

  1. html5 人物行走

    键盘方向键控制人物上下左右行走 演示地址 点击打开链接 MYCode <html> <head> <meta charset=utf-8> <title> ...

  2. Git命令行连Github与TortoiseGit 连Github区别

    如果是用git 通过命令行的方式连接github,那么只需要通过命令 $ ssh-keygen -t rsa -C "your_email@youremail.com" 生成rsa ...

  3. KingPaper初探 wamp下本地虚拟主机的搭建

    在本地我们进行网站或系统开发时,因为我们本地的地址以localhost为主机名的  我们上传到服务器会有很多东西要修改 为了避免这些不必要的修改,我们可以在本地搭建虚拟主机 一下是在wamp下搭建虚拟 ...

  4. VIM 多行输入 数字递增 新方法 循环记录法

    采用的是mario register这个方法,然后,把一段 auto-increament 操作记录下来,然后playback 循环往复多次.就达到了,每行都递增的目的. 我写的文字如下: vim 输 ...

  5. iOS extern使用教程

    ios开发使用extern访问全局变量 使用extern关键字法: 1 .新建Constants.h文件(文件名根据需要自己取),用于存放全局变量: 2. 在Constants.h中写入你需要的全局变 ...

  6. Java8:使用Lambda表达式增强版Comparator排序

    学习路上的自我记录-------路好长,就问你慌不慌,大声港,不慌.----jstarseven. 实体类: package com.server.model; /** * Created by js ...

  7. Json 使用小结

    关于Json: content={ news_item=[ { title=a, digest=tan for test, content=just for test, content_source_ ...

  8. Python print报ascii编码异常的靠谱解决办法

    之前遇到此异常UnicodeEncodeError: 'ascii' codec can't encode characters...,都是用这种方式解决:sys.setdefaultencoding ...

  9. 用C++实现的元胞自动机

    我是一个C++初学者,控制台实现了一个元胞自动机. 代码如下: //"生命游戏"V1.0 //李国良于2017年1月1日编写完成 #include <iostream> ...

  10. jq,js简单实现类似Angular.js数据绑定效果

    刚了解了下Angular.js,发现Angular.js绑定数据方面非常方便,套下教程demo: <div ng-app="myApp" ng-controller=&quo ...