Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.NET MVC Routing概述 C#描述

ASP.NET MVC Routing概述 C#描述2013-11-28 cnblogs JasenKinASP.NET Routing模块的责任是将传入的浏览器请求映射为特有的MVC controller actions。

使用 默认的Route Table

当你创建一个新的ASP.NET MVC应用程序,这个应用程序已经被配置用来使用ASP.NET Routing。 ASP.NET Routing 在2个地方设置。第一个,ASP.NET Routing 在你的应用程序中的Web配置文件( Web.config文件)是有效的。在配置文件中有4个与routing相关的代码片段:system.web.httpModules代码段 ,system.web.httpHandlers 代码段,system.webserver.modules代码段以及 system.webserver.handlers代 码段。千万注意不要删除这些代码段,如果没有这些代码段,routing将不再运行。第二个,更重要的,route  table在应用程序的Global.asax文件中创建。这个Global.asax文件是一个特殊的文件,它包含ASP.NET 应用程序生命周期events的event handlers。这个route  table在应用程序的起始event中创将。

在Listing 1中包含ASP.NET MVC应用程序的默认Global.asax文件.

Listing 1 - Global.asax.cs

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 public class MvcApplication : System.Web.HttpApplication{public static void RegisterRoutes(RouteCollection routes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute("Default", // 路由名称"{controller}/{action}/{id}", // 带有参数的 URLnew { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值);}protected void Application_Start(){AreaRegistration.RegisterAllAreas();RegisterRoutes(RouteTable.Routes);}}
当一个MVC应用程序第一个启动,Application_Start() 方法被调用,这个方法反过来调用 RegisterRoutes() 方法。

这个默认的route  table包含一个单一的route。这个默认的route将 url的第一个段映射为一个controller名称,url的第二个段映射为一个controller  action,第三个段映 射为命名为id的参数。

假如,你在网页浏览器的地址栏中键入下面的url:/Home/Index/3,这个默认的 route将这个url映射为下面的参数:

controller = Home     controller名称

action = Index          controller  action

id = 3                       id的参数

当你请 求/Home/Index/3这样的url,下面的代码将执行。HomeController.Index(3)

这个默认的route包含3个 默认的参数。如果你没有提供一个 controller,那么 controller默认为Home。同样,action默认为Index,id 参数默认为空字符串。

让我们来看一些关于默认的route怎么映射urls为controller  actions的例 子。假如你在你的浏览器地址栏中输入如下的url:/Home, 由于这些默认的route参数有一些相关的默认值, 键入这样的URL,将导致HomeController类的Index()方法(如Listing 2)被调用。

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 namespace MvcRoutingApp.Controllers{[HandleError]public class HomeController : Controller{public ActionResult Index(string id){ViewData["Message"] = "欢迎使用 ASP.NET MVC!";return View();}public ActionResult About(){return View();}}}