ASP.NET 路由使您可以处理未映射到 Web 应用程序中物理文件的 URL 请求。默认情况下,在动态数据或 MVC 框架的一个 ASP.NET 应用程序中启用 ASP.NET 路由,而不在 ASP.NET 网站项目中启用路由。因此,若要在 ASP.NET 网站中使用路由,必须采取措施来启用。
若要启用路由,必须更改应用程序的配置文件来注册路由程序集,并添加 UrlRoutingModule 类作为模块。还必须为路由创建一个自定义路由处理程序。该处理程序实现 IRouteHandler 接口并创建 Web 窗体(.aspx 文件)的一个实例,该实例将为请求的实际终结点。最后,必须定义处理程序所提供的路由。本主题演示如何执行这些步骤。
Watch a video(观看视频)演示了此功能。
配置用于路由的 ASP.NET 网站项目
-
在应用程序的 Web.config 文件中,将 ASP.NET 路由程序集添加到 assemblies 元素,如下面的示例所示:
<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
-
如果应用程序在 IIS 6.0 或 IIS 7.0 经典模型下运行,则将 UrlRoutingModule 类添加到 httpModules 元素,如下面的示例所示:
<httpModules> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpModules>
-
如果应用程序在 IIS 7.0 集成模式下运行,则将 UrlRoutingModule 类添加到 modules 元素,如下面的示例所示:
<system.webServer> <modules> <remove name="UrlRoutingModule" /> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> </system.webServer>
-
如果应用程序在 IIS 7.0 集成模式下运行,则将 UrlRoutingHandler 类添加到 handlers 元素,如下面的示例所示:
<system.webServer> <handlers> <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </handlers> </system.webServer>
创建处理程序
-
创建实现 IRouteHandler 接口的类。
-
实现 GetHttpHandler 方法。若要指定一个特定的 Web 窗体(.aspx 文件)作为请求的终结点,请从 GetHttpHandler 方法返回该 Web 窗体的一个实例。
下面的示例演示一个名为 CustomRouteHandler 并实现 IRouteHandler 接口的类。GetHttpHandler 方法调用 CreateInstanceFromVirtualPath 方法创建指定 Web 窗体的一个实例。该实例作为请求的终结点返回。
public class CustomRouteHandler : IRouteHandler { public CustomRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; private set; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { var page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler; return page; } }
注册自定义处理程序
-
如果 Web 应用程序还没有 Global.asax 文件,请添加。
-
将导入 System.Web.Routing 命名空间的指令添加到 Global.asax 文件中,如下面的示例所示:
<%@ Import Namespace="System.Web.Routing" %>
-
在 Global.asax 文件中创建一个方法,该方法将路由定义添加到 RouteTable 类的 Routes 属性中。
-
从 Application_Start 事件处理程序中调用该方法。
下面的示例演示一个方法,该方法注册了一个名为 CustomRouteHandler 的类作为匹配 bikes/sale 的请求的处理程序。
void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.Add("BikeSaleRoute", new Route ( "bikes/sale", new CustomRouteHandler("~/Contoso/Products/Details.aspx") )); }