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加载的插件程序集添加到应用程序域的引用中.具体 ...
随机推荐
- 机器学习:Python实现单层Rosenblatt感知器
如果对Rosenblatt感知器不了解,可以先查看下相关定义,然后对照下面的代码来理解. 代码中详细解释了各步骤的含义,有些涉及到了数学公式的解释. 这篇文章是以理解Rosenblatt感知器的原理为 ...
- PRINCE2重要性--光环国际培训
项目的重要性 答:对于当今的组织来说,一个关键的挑战,就是能够成功地平衡以下两个并存的.互相竞争的方面:保持现有的商业运营--盈利能力.服务质量.客户关系.品牌忠实度.生产效率.市场信心等,这些被称为 ...
- 判断是否是IE(包含IE11)
判断是否是IE(包含IE11) if(!!window["ActiveXObject"] || "ActiveXObject" in window) { ale ...
- 学习面向对象编程OOP 第二天
好,今天继续学习这个面向对象编程.(根据博客园 小炒花生米写的博客学习而来) 一,封装性 a.把对象的全部属性和全部服务(方法)结合在一起,形成一个不可分割的独立单元 =>对象 b.信息隐蔽,尽 ...
- CSS3-渐变背景色
线性渐变背景色: <style> .linear { width:130px; height:130px; border:2px solid black; padding: 10px; b ...
- 前馈神经网络-反向传播(Back Propagation)公式推导走读
构造:输入神经元个数等于输入向量维度,输出神经元个数等于输出向量维度.(x1=(1,2,3),则需要三个输入神经元) 一 前向后传播 隐层:
- Coordinator节点
Coordinator节点 Coordinator 节点主要负责segment 的管理和分配.更具体的说,它同通过配置往historical 节点 load 或者 drop segment .Coo ...
- CSAcademy Beta Round #5 Force Graph
题目链接:https://csacademy.com/contest/arhiva/#task/force_graph/ 大意是有若干个节点,每个节点对应一个二维坐标,节点之间相互有斥力存在.同时有些 ...
- oracle 的 SDO_GEOMETRY
元数据定义 CREATE OR REPLACE TYPE MDSYS.SDO_GEOMETRY AS OBJECT ( SDO_GTYPE NUMBER, SDO_SRID NUMBER, SDO_P ...
- js日期转化(计算一周的日期)
之前做项目的时候遇到过一个日期转化的问题,一个日期控件和近一天,近七天和近一月的的联动效果.发现自己不会,后来就百度了一下解决了这个问题. 现在抽空又写了一个时间转化的案例(计算一周的日期),因为之前 ...