路由程式集System.Web.Routing位於.NET架構3.5的SP1版本中,是與ASP.NET3.5 MVC分離的,所以在傳統的Web Form項目中也可以使用路由。
ASP.NET 路由使您可以處理未映射到 Web 應用程式中物理檔案的 URL 請求。預設情況下,在動態資料或 MVC 架構的一個 ASP.NET 應用程式中啟用 ASP.NET 路由,而不在 ASP.NET 網站項目中啟用路由。
因此,若要在 ASP.NET 網站中使用路由,必須採取措施來啟用。
要實現在WebForm中使用路由,首先需要建立實現IRouteHandler介面的WebFormRouteHandler類,然後在全域應用程式類中配置路由的映射就可以了。
WebFormRouteHandler代碼如下:
using System.Web;using System.Web.Compilation;using System.Web.Routing;using System.Web.UI;namespace MVCWebApplication1{ public class WebFormRouteHanlder : IRouteHandler { public string VirtualPath { get; private set; } public WebFormRouteHanlder(string virtualPah) { VirtualPath = virtualPah; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler; return page; } }}
在Global.asax中配置路由:
using System;using System.Web.Routing;namespace MVCWebApplication1{ public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.Add("Named", new Route("foo/bar", new WebFormRouteHanlder("~/forms/blech.aspx"))); routes.Add("Number", new Route("one/two/three", new WebFormRouteHanlder("~/forms/haha.aspx"))); } }}
還需要在Web.config中配置System.Web.Routing的引用!
<httpModules> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpModules>
運行,訪問http://localhost:5598/foo/bar 。OK~~~~
參考:MSDN,MVC架構與實戰 地址:如何:MSDN協助 對 Web Form使用路由