認識 ASP.NET 3.5 MVC 路由 在WebForm項目中使用路由

來源:互聯網
上載者:User

路由程式集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使用路由

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.