您现在的位置是:网站首页> 编程资料编程资料

ASP.NET MVC中的路由原理与用法_实用技巧_

2023-05-24 451人已围观

简介 ASP.NET MVC中的路由原理与用法_实用技巧_

一、概述

在ASP.NET MVC架构中,控制器在3大核心构件中处于中心地位,通过控制器支配模型和视图,然而从浏览器发出的请求到控制器还需要路由的协助,路由将特定的请求和控制器的动作对应起来。

在ASP.NET MVC程序中,路由主要有两方面的职责:

  • 与入站的请求相匹配,将这些请求映射到控制器的动作中。
  • 构造出站的URL,这些URL可以响应控制器的动作。

二、路由原理

1、注册路由

先看Global.asax中的代码:

网站启动的时候执行Application_Start方法,通过RouteConfig.RegisterRoutes(RouteTable.Routes)这段代码进行路由的注册,在RegisterRoutes上面F12转到定义,可以查看该方法,其实就是App_Start文件夹下面的RouteConfig类,该类定义如下:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ASPNETMVCDemo { ///  /// RouteCollection 所有路由的集合 ///  public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { // 表示忽略路由 只要URL满足这个正则规则,就不使用路由 // .axd 是因为iis6给没有后缀的请求加个asd,然后支持MVC的请求 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // 默认路由规则 // 里面使用的是命名参数,顺序可以改变 routes.MapRoute( // 路由名称 RouteCollection是个字典 每个路由都要有自己的名称,相同名称的路由会被覆盖 name: "Default", // url的正则规则,去掉域名和端口后的地址进行匹配 url: "{controller}/{action}/{id}", // 默认值 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }

注册路由其实就是把路由规则添加到RouteCollection路由集合中。

解释说明:

  • RegisterRoutes方法是在应用程序启动时(Application_Start)被调用执行的。
  • RegisterRoutes方法的作用:注册路由。它的参数是一个集合对象,这个集合对象就是用来保存多项路由数据的。一项路由数据实际上就是某种形式的URL路径和控制器及其Action的关系,根据这个关系,MVC才能执行到控制器。
  • 那么怎么添加这种路由数据呢?即调用RegisterRoutes方法里面的routes.MapRoute方法。该方法的第一个参数是路由的名称,类似于Dictionary字典里面的key。第二个参数表示的是URL或者是地址。第三个参数是一个匿名类型,表示该路由相关的默认数据,可以看作一个字典。
  • 我们注意到第二个参数其实就是占位符表示的URL,这个占位符是用大括号和里面的字符串表示的。可以看出里面不是某种硬编码的URL地址(这里的controller代表所有的控制器,而不是某一个具体的控制器。同理,action也是代表所有的方法,而不是某一个具体的action方法),这样就增加了灵活性,就是用“/”把URL分成三部分。还有我们注意到占位符表示的URL是没有域名的,这个是允许的,这种匹配是不考虑域名的。
  • 在ASP.NET MVC中我们见得最多的是“{controller}/{action}/{id}”这种形式的URL,那么controller和action这两个单词是否有特殊的用途呢,能不能改变这两个单词的写法。答案是不能的。这时因为会把controller、action和id当做字典或集合的key值来存储对应的URL片段,这样框架在处理时,会读取键名为controller的数据,比如Home,然后得到要执行的控制器是HomeController。同样会从字典中读取键名为action的数据,比如Index,然后得到要执行的Action方法是Index。如果这两个单词写错了,就执行不到相应的controller和action方法了。所以一定要记住写成controller和action是一种约定,其他参数的定义就没有这种要求了。但是action和controller的位置可以修改。

启动程序,这时URL地址是:http://localhost:49730

其实该地址相当于在浏览器里面输入:http://localhost:49730/Home/Index,这时因为在路由规则里面设置了默认值,如果没有控制器和action方法,则默认是Home控制器下面的Index方法。

修改URL里面的controller和action,代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ASPNETMVCDemo { ///  /// RouteCollection 所有路由的集合 ///  public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { // 表示忽略路由 只要URL满足这个正则规则,就不使用路由 // .axd 是因为iis6给没有后缀的请求加个asd,然后支持MVC的请求 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // 默认路由规则 // 里面使用的是命名参数,顺序可以改变 routes.MapRoute( // 路由名称 RouteCollection是个字典 每个路由都要有自己的名称,相同名称的路由会被覆盖 name: "Default", // url的正则规则,去掉域名和端口后的地址进行匹配 url: "{controller1}/{action1}/{id}", // 默认值 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }

然后运行程序查看结果:

这时程序运行出错,所以说controller和action千万不能写错。把controller和action改回正确的,然后颠倒controller和action的位置,代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ASPNETMVCDemo { ///  /// RouteCollection 所有路由的集合 ///  public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { // 表示忽略路由 只要URL满足这个正则规则,就不使用路由 // .axd 是因为iis6给没有后缀的请求加个asd,然后支持MVC的请求 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // 默认路由规则 // 里面使用的是命名参数,顺序可以改变 routes.MapRoute( // 路由名称 RouteCollection是个字典 每个路由都要有自己的名称,相同名称的路由会被覆盖 name: "Default", // url的正则规则,去掉域名和端口后的地址进行匹配 url: "{action}/{controller}/{id}", // 默认值 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }

在运行程序查看结果:

这说明:controller和action的位置是可以颠倒的。这时如果想输入完整的URL地址就行访问就应该输入:http://localhost:49730/Index/Home。

2、路由匹配

2.1、匹配方式一

看下面的截图:

解释说明:

  • {parameter}:花括弧加任意长度的字符串表示模糊匹配,字符串不能定义成controller和action。默认路由规则就是使用模糊匹配,没有指明具体是哪个控制器里面的哪个action方法。
  • 字面量即一个常数字符串,这个字符串可以在大括弧与大括弧之间,也可以在最前面或最后面。
  • 两个大括弧之间没有任何的字面量是不可以的。

看下面的示例:

首先修改Home控制器里面的Index方法,修改后的代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ASPNETMVCRoute.Controllers { public class HomeController : Controller { public ActionResult Index() { string paras = ""; // 遍历获取参数值 foreach(KeyValuePair keyValue in RouteData.Values) { paras += string.Format($"{keyValue.Key}={keyValue.Value} "); } // 通过ViewData向页面传值 ViewData["msg"] = paras; return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }

修改对应的视图,在界面展示ViewData["msg"]的值:

@{ ViewBag.Title = "Home Page"; } 

ASP.NET

ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.

Learn more »

@ViewData["msg"]

Getting started

ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development.

Learn more »

Get more libraries

NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

Learn more »

Web Hosting

You can easily find a web hosting company that offers the right mix of features and price for your applications.

Learn more »

1、使用{parameter}做模糊匹配其实就是默认路由规则:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

运行程序查看结果:

2、使用字面量做精确匹配

路由规则如下代码所示:

routes.MapRoute( name: "const", url: "admin/{controller}/{action}" );

运行程序,在浏览器里面输入:http://localhost:64957/admin/home/index,运行结果如下:

3、不允许连续的URL参数

路由规则如下:

routes.MapRoute( name: "blx", // 错误的URL // url: "{language}{country}/{controller}/{action}" url: "{language}-{country}/{controller}/{action}" );<
                
                

-六神源码网