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加载的插件程序集添加到应用程序域的引用中.具体 ...
随机推荐
- Appium手势密码滑动之Z字形走势(java篇)
1.直接使用负的偏移量appium会报错,在后面加上moveto(1,1)就行了 2.直接看图说话 废话少说看代码如: List<AndroidElement> element = dri ...
- window7使用svn(svn系列 客户端 知识二总结)
♣eclipse插件subclipse ♣TortoiseSVN ♣svn操作 ♣注意事项 使用svn可以在eclipse直接装subclipse或者在windows使用TortoiseSVN ...
- 用webpack搭建react开发环境
安装插件: npm install react react-dom babel-loader babel-core babel-preset-react babel-preset-es2015 配置w ...
- js动弹特效
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 网站与域名知识扫盲-DNS
域名概述 域名的概念 IP地址不易记忆 早期使用Hosts解析域名 主机名称重复 主机维护困难 DNS(Domain Name System 域名系统) 分布式 层次性 域名空间结构 根域 组织域[. ...
- Java使用递归找出某目录下的所有子目录以及子文件
/* 使用递归找出某目录("C:\\JavaProducts")下的所有子目录以及子文件 */ import java.util.*; import java.io.*; publ ...
- PHP站内搜索
1.SQL语句中的模糊查找 LIKE条件一般用在指定搜索某字段的时候, 通过"% 或_" 通配符的作用实现模糊查找功能,通配符可以在前面也可以在后面或前后都有. 搜索以PHP100 ...
- 【HDOJ 2150】线段交叉问题
Pipe Time Limit : 1000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other) Total Submissi ...
- mvc中DotNetOpenAuth实现了第三方应用访问自己的网站
以yahoo为例吧,即从yahoo取得用户信息,存到自己的站点,实现了用户信息在一次录入多处共享的功能.以下是在点击了使用yahoo登录本站的链接后执行action:OpenId. ProviderU ...
- Eclipse实现图形化界面插件-vs4e
vs4e插件下载地址:http://visualswing4eclipse.googlecode.com/files/vs4e_0.9.12.I20090527-2200.zip 下载完成后,解压,然 ...