ASP.NET MVC5路由系统机制详细讲解
请求一个ASP.NET mvc的网站和以前的web form是有区别的,ASP.NET MVC框架内部给我们提供了路由机制,当IIS接受到一个请求时,会先看是否请求了一个静态资源(.html,css,js,图片等),这一步是web form和mvc都是一样的,如果不是则说明是请求的是一个动态页面,就会走asp.net的管道,mvc的程序请求都会走路由系统,会映射到一个Controller对应的Action方法,而web form请求动态页面是会查找本地实际存在一个aspx文件。下面通过一个ASP.NET MVC5项目来详细介绍一下APS.NET MVC5路由系统的机制。
一、认识Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//注册 ASP.NET MVC 应用程序中的所有区域
AreaRegistration.RegisterAllAreas();
//注册 全局的Filters
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
//注册 路由规则
RouteConfig.RegisterRoutes(RouteTable.Routes);
//注册 打包绑定(js,css等)
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
这个Application_Start方法会在网站启动的自动调用,其中我们看到:RouteConfig.RegisterRoutes(RouteTable.Routes);这个就是向ASP.NET MVC 框架注册我们自定义的路由规则,让之后的URL能够对应到具体的Action。接下来我们再来看看RegisterRoutes方法做了些什么?
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
二、ASP.NET MVC默认的命名约定
1、Controller命名约定
2、View命名约定
三、ASP.NET MVC的URL规则说明

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
|
URL
|
URL段 |
|
http://mysite.com/Admin/Index
|
controller = Admin
action = Index
|
|
http://mysite.com/Index/Admin
|
controller = Index
action = Admin
|
|
http://mysite.com/Apples/Oranges
|
controller = Apples
action = Oranges
|
|
http://mysite.com/Admin
|
无匹配-段的数量不够
|
|
http://mysite.com/Admin/Index/Soccer
|
无匹配-段的数量超了 |
四、mvc创建一个简单的Route规则
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}");
}
用到了RouteCollection的MapRoute方法。其实我们还可以调用 Add方法,传一个Route的实例给它一样的达到相同的效果。
public static void RegisterRoutes(RouteCollection routes) {
Route myRoute = new Route("{controller}/{action}", new MvcRouteHandler());
routes.Add("MyRoute", myRoute);
}
五、mvc路由的默认值的设定
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}", new { action = "Index" });
}
要设置Controller和Action的默认值。
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}",
new { controller = "Home", action = "Index" });
}
|
Url段的数量
|
实例
|
Route映射
|
|
0
|
mydomain.com
|
controller = Home
action = Index
|
|
1
|
mydomain.com/Customer
|
controller = Customer
action = Index
|
|
2
|
mydomain.com/Customer/List
|
controller = Customer
action = List
|
|
3
|
mydomain.com/Customer/List/All
|
无匹配—Url段过多
|
六、mvc使用静态URL段
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("", "Public/{controller}/{action}",
new { controller = "Home", action = "Index" });
}
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("", "X{controller}/{action}");
routes.MapRoute("MyRoute", "{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("", "Public/{controller}/{action}",
new { controller = "Home", action = "Index" });
}
七、mvc的路由中自定义参数变量
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
}
public ViewResult CustomVariable() {
ViewBag.CustomVariable = RouteData.Values["id"];
return View();
}
public ViewResult CustomVariable(int id) {
ViewBag.CustomVariable = id;
return View();
}
MVC框架使用内置的Model绑定系统将从URL获取到变量的值转换成Action参数相应类型的值。这种转换除了可以转换成基本int,string等等之外还可以处理复杂类型,自定义的Model,List集合等。
八、mvc定义可选URL段、可选参数
1、注册路由时定义可选URL段
2、通过Action参数来定义可选参数
九、mvc使用*来定义变长数量的URL段
|
Url段的数量
|
实例
|
Route映射
|
|
0
|
mydomain.com
|
controller = Home
action = Index
|
|
1
|
mydomain.com/Customer
|
controller = Customer
action = Index
|
|
2
|
mydomain.com/Customer/List
|
controller = Customer
action = List
|
|
3
|
mydomain.com/Customer/List/All
|
controller = Customer
action = List
id = All
|
|
4
|
mydomain.com/Customer/List/All/Delete
|
controller = Customer
action = List
id = All
catchall = Delete
|
|
5
|
mydomain.com/Customer/List/All/Delete/Perm
|
controller = Customer
action = List
id = All
catchall = Delete /Perm
|
十、mvc使用命名空间来为路由的Controller类定优先级
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new string[] { "WebApplication1.Controllers" }
);
}
十一、mvc定义路由规则的约束
1、用正则表达式限制asp.net mvc路由规则
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^H.*"},
new[] { "URLsAndRoutes.Controllers"});
}
2、把asp.net mvc路由规则限制到到具体的值
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^H.*", action = "^Index$|^About$"},
new[] { "URLsAndRoutes.Controllers"});
}
上例在controller和action上都定义了约束,约束是同时起作用是,也就是要同时满足。上面表示只匹配contorller名字以H开头的URL,且action变量的值为Index或者为About的URL。
3、把asp.net mvc路由规则限制到到提交请求方式(POST、GET)
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^H.*", action = "Index|About",
httpMethod = new HttpMethodConstraint("GET") },
new[] { "URLsAndRoutes.Controllers" });
}
上面表示只匹配为GET方式的请求。
4、使用接口IRouteConstraint自定义一个asp.net mvc路由约束
using System.Web;
using System.Web.Routing; namespace URLsAndRoutes.Infrastructure { public class UserAgentConstraint : IRouteConstraint {
private string requiredUserAgent; public UserAgentConstraint(string agentParam) {
requiredUserAgent = agentParam;
} public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection) { return httpContext.Request.UserAgent != null &&
httpContext.Request.UserAgent.Contains(requiredUserAgent);
}
}
}
asp.net mvc自定义路由约束的使用:
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {
controller = "^H.*", action = "Index|About",
httpMethod = new HttpMethodConstraint("GET", "POST"),
customConstraint = new UserAgentConstraint("IE")
},
new[] { "URLsAndRoutes.Controllers" });
}
十二、mvc将URL路由到磁盘文件
public static void RegisterRoutes(RouteCollection routes) {
routes.RouteExistingFiles = true;
routes.MapRoute("DiskFile", "Content/StaticContent.html",
new {
controller = "Account", action = "LogOn",
},
new {
customConstraint = new UserAgentConstraint("IE")
});
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {
controller = "^H.*", action = "Index|About",
httpMethod = new HttpMethodConstraint("GET", "POST"),
customConstraint = new UserAgentConstraint("IE")
},
new[] { "URLsAndRoutes.Controllers" });
}
我们把RouteExistingFiles属性设置为true,表示存在的文件也走路由,上面我们把Content/StaticContent.html这个文件映射到controller 为Account,action 为LogOn中了,而并不是指磁盘中存在的文件。基于asp.net mvc的这个特性我们就可以实现mvc以.html结尾的伪静态
十三、mvc跳过、绕开路由系统设定
public static void RegisterRoutes(RouteCollection routes) {
routes.RouteExistingFiles = true;
routes.MapRoute("DiskFile", "Content1/StaticContent.html",
new {
controller = "Account", action = "LogOn",
},
new {
customConstraint = new UserAgentConstraint("IE")
});
routes.IgnoreRoute("Content/*{filename}");
routes.MapRoute("", "{controller}/{action}");
}
ASP.NET MVC5路由系统机制详细讲解的更多相关文章
- MVC5路由系统机制详细讲解
请求一个ASP.NET mvc的网站和以前的web form是有区别的,ASP.NET MVC框架内部给我们提供了路由机制,当IIS接受到一个请求时,会先看是否请求了一个静态资源(.html,css, ...
- ASP.NET的路由系统
一.URL与物理文件的分离 1.URL与物理文件的分离 对于一个 ASP.NET Web Form应用来说,任何一个请求都对应着某个具体的物理文件.部署在Web服务器上的物理文件可以是静态的(比如图片 ...
- ASP.NET的路由系统:路由映射
总的来说,我们可以通过RouteTable的静态属性Routes得到一个基于应用的全局路由表,通过上面的介绍我们知道这是一个类型的RouteCollection的集合对象,我们可以通过调用它的MapP ...
- ASP.NET MVC , ASP.NET Web API 的路由系统与 ASP.NET 的路由系统是怎么衔接的?
ASP.NET MVC 的路由实际上是建立在 ASP.NET 的路由系统之上的. MVC 路由注册通常是这样的: RouteTable 是一个全局路由表, 它的 Routes 静态属性是一个 Ro ...
- asp.net MVC 路由系统
ASP.NET的路由系统是基于物理文件的路由注册,通过调用System.Routing.RouteTable的Routes(RouteCollection)属性的MapPageRoute()方法来完成 ...
- ASP.NET MVC5+ 路由特性
概述 ASP.NET MVC 5支持一种新的路由协议,称为路由特性. MVC5也支持以前定义路由的方式,你可以在一个项目中混合使用这两种方式来定义路由. 案例 1.使用Visual Studio 20 ...
- Django框架----路由系统(详细)
Django的路由系统 Django 1.11版本 URLConf官方文档 URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL与要为该URL调用的视图函数之间的映射表. ...
- Asp.net MVC5 路由Html后缀的问题
环境:VS2013+MVC5+IIS EXPRESS 问题:如果从Asp.net Web迁移到MVC,可能会遇到需要使原来的链接(如http://localhost:12345/old/library ...
- ASP.NET MVC5 插件化机制简单实现
一.前言 nopCommerce的插件机制的核心是使用BuildManager.AddReferencedAssembly将使用Assembly.Load加载的插件程序集添加到应用程序域的引用中.具体 ...
随机推荐
- 【CreateJS】WebStorm+Adobe Animate CC 搭配开发HTML5,入门教程
目的:动画设计师用Adobe Animate CC做好动画素材,发布好之后,交给程序员写交互代码:在WebStorm之类的ide里操纵 Animate 里面的变量,class等. 前提环境: ①安装好 ...
- Java基础之面试题
本文我们将要讨论Java面试中的各种不同类型的面试题,它们可以让雇主测试应聘者的Java和通用的面向对象编程的能力.下面的章节分为上下两篇,第一篇将要讨论面向对象编程和它的特点,关于Java和它的功能 ...
- [原]node.js使用感想
最近尝试了使用node.js,但因为不是太深入(小项目,还没做完),所以不能谈心得谈经验,就来谈谈使用感想. node.js和以往的cgi接口的服务器+cgi程序(如apache+phpmod)中的单 ...
- 老李分享:《Linux Shell脚本攻略》 要点(一)
老李分享:<Linux Shell脚本攻略> 要点(一) 第一章:Shell起步基础 1.变量:在bash中,每一个变量的值都是字符串.无论你给变量赋值时,有没有使用引号,值都会以字符 ...
- Dubbo配置方式详解
Dubbo 是一个分布式服务框架,致力于提供高性能和透明化的 RPC 远程服务调用方案,是阿里巴巴 SOA 服务化治理方案的核心框架,每天为 2,000+ 个服务提供 3,000,000,000+ 次 ...
- C# Task 源代码(2)
上篇已经讲到Task 的默认的TaskScheduler 为ThreadPoolTaskScheduler. 这时我们回到原来的task 的start方法,在代码最后,调用了 ScheduleAndS ...
- 管中窥豹——从对象的生命周期梳理JVM内存结构、GC调优、类加载、AOP编程及性能监控
如题,本文的宗旨既是透过对象的生命周期,来梳理JVM内存结构及GC相关知识,并辅以AOP及双亲委派机制原理,学习不仅仅是海绵式的吸收学习,还需要自己去分析why,加深对技术的理解和认知,祝大家早日走上 ...
- python 日期 & 时间
1. Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间. 2. 时间间隔是以秒为单位的浮点小数. 3. 每个时间戳都以自从1970年1月1日午夜(历元)经过了多长 ...
- java 基础知识六 字符串1
java 基础知识六 字符串1 String 不是java的基本数据类型 String 不是java的基本数据类型 String 不是java的基本数据类型 字符串是是一个字符序列 1.创建 创建 ...
- js alert(“”)弹框 自定义样式
首先用css渲染一个样式 #msg{ height: 2rem; text-align: center; position: fixed; top: 50%; margin-top: -1rem; l ...