UserAgentConstraint.cs:
- 1 using System.web;
- 2 using System.Web.Routing;
- 3
- 4 namespace URLsAndRoutes.Infrastructure {
- 5
- 6 public class UserAgentConstraint : IRouteConstraint {
- 7 private string requiredUserAgent;
- 8
- 9 publicUserAgentConstraint(string agentParam) {
- 10requiredUserAgent = agentParam;
- 11 }
- 12
- 13 public boolMatch(HttpContextBase httpContext, Route route,string parameterName,
- 14 RouteValueDictionary values, RouteDirection routeDirection) {
- 15
- 16 returnhttpContext.Request.UserAgent !=null&&17 httpContext.Request.UserAgent.Contains(requiredUserAgent);
- 18 }
- 19 }
- 20}
asp.net mvc 自定义路由约束的使用:
- 1 public static void RegisterRoutes(RouteCollection routes) {
- 2 3 routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", 4 new {
- controller = "Home",
- action = "Index",
- id = UrlParameter.Optional
- },
- 5 new {
- 6 controller = "^H.*",
- action = "Index|About",
- 7 httpMethod = new HttpMethodConstraint("GET", "POST"),
- 8 customConstraint = new UserAgentConstraint("IE") 9
- },
- 10 new[] {
- "URLsAndRoutes.Controllers"
- });
- 11
- }
上面表示这个路由规则只匹配用户使用 IE 浏览器的请求。利用这点我们就可以实现不同浏览器使用不同的 Controller,进行不同的处理。虽然这样做的意义不大,但是不排除有时会有这种变态的需求。
这种默认的处理 url 机制顺序我们也可以改变它,让在检查物理文件之前就应用路由,如下:
mvc 的网站并不是所以的 url 请求都是对应 controller,action,我们仍然要一种方式来提供一些静态内容,比如:html 文件,CSS, 图片, javascript 文件些,其实默认情况下 mvc 框架在在收到 url 请求时会先判断这个 url 是否是对应一个磁盘中真实存在的文件,如果是直接返回,这时路由是没有使用到的,如果不是真实存在的文件时才会走路由系统,再去匹配注册的路由规则。
- 1 public static void RegisterRoutes(RouteCollection routes) {
- 2 3 routes.RouteExistingFiles = true;
- 4 5 routes.MapRoute("DiskFile", "Content/StaticContent.html", 6 new {
- 7 controller = "Account",
- action = "LogOn",
- 8
- },
- 9 new {
- 10 customConstraint = new UserAgentConstraint("IE") 11
- });
- 12 13 routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", 14 new {
- controller = "Home",
- action = "Index",
- id = UrlParameter.Optional
- },
- 15 new {
- 16 controller = "^H.*",
- action = "Index|About",
- 17 httpMethod = new HttpMethodConstraint("GET", "POST"),
- 18 customConstraint = new UserAgentConstraint("IE") 19
- },
- 20 new[] {
- "URLsAndRoutes.Controllers"
- });
- 21
- }
我们把 RouteExistingFiles 属性设置为 true,表示存在的文件也走路由,上面我们把 Content/StaticContent.html 这个文件映射到 controller 为 Account,action 为 LogOn 中了,而并不是指磁盘中存在的文件。基于 asp.net mvc 的这个特性我们就可以实现 mvc 以. html 结尾的伪静态
上面我们用使用 routes.RouteExistingFiles = true,让所有的请求都走路由系统过一下,难免有一些性能影响,因为一些图片,一些真正的 html,文件是没有必要的。我们可以对些文件做一些起特殊设定让它们跳过、绕开路由系统。下面就是让 Content 目录下的所有文件都绕开 mvc 的路由系统:
- 1 public static void RegisterRoutes(RouteCollection routes) {
- 2
- 3routes.RouteExistingFiles =true;
- 4
- 5routes.MapRoute("DiskFile","Content1/StaticContent.html",
- 6 new {
- 7controller ="Account", action ="LogOn",
- 8 },
- 9 new {
- 10customConstraint =newUserAgentConstraint("IE")
- 11 });
- 12
- 13routes.IgnoreRoute("Content/*{filename}");
- 14routes.MapRoute("","{controller}/{action}");
- 15
- 16}
来源: http://www.cnblogs.com/itliuyang/p/6872027.html