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