在 ASP.NET MVC 項目中使用 WebForm

來源:互聯網
上載者:User

ASP.NET MVC和WebForm各有各的優點,我們可能需要同時使用ASP.NET MVC和WebForm。本文介紹了如何在ASP.NET MVC項目中使用WebForm。
首先建立一個名為WebForms的檔案夾用於存放WebForm,並添加一個Web表單檔案Demo.aspx作為示範。

Demo.aspx就簡單的輸出一句話“It’s a WebForm.”
關鍵步驟在於路由設定。如果你希望WebForms這個檔案夾名作為URL的一部分,也就是普通WebForm應用程式的方式來訪問這個Demo.aspx,那麼只需要簡單的忽略這個路由規則即可。
在Global.asax.cs檔案的RegisterRoutes方法中加入以下代碼 

// 忽略對 WebForms 路徑的路由
routes.IgnoreRoute("WebForms/{weform}");

 結果:

如果希望URL更友好或者不出現WebForms這個檔案夾名,那就要自己寫一個類繼承IRouteHandler。

 1public class WebFormsRouteHandler:IRouteHandler
 2{
 3    private string pageName = string.Empty;
 4
 5    public IHttpHandler GetHttpHandler(RequestContext requestContext)
 6    {
 7        // 從URL中擷取page參數
 8        pageName = requestContext.RouteData.GetRequiredString("page");
 9
10        // 建立執行個體
11        // 根據 page 參數拼接成類似/WebForms/page.aspx地址來訪問WebForms頁面
12        IHttpHandler hander = BuildManager.CreateInstanceFromVirtualPath("/WebForms/" + this.pageName+".aspx", typeof(System.Web.UI.Page)) as IHttpHandler;
13
14        return hander;
15    }
16
17}

 

然後在Global.asax.cs檔案中加上新的路由規則

// 添加一個用WebFormsRouteHandler進行處理的路由
// 其中URL中{page}所佔的部分會被在WebFormsRouteHandler中當做參數使用
routes.Add(new Route("web/{page}",new WebFormsRouteHandler()));

 

當路徑匹配web/{page}時用自訂的類來處理這個請求,如web/demo或web/demo1等URL都會匹配到這個路由

樣本下載

 

本文適用於 ASP.NET MVC 1.0

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.