不走尋常路:在WebForm中使用MVC

作者: dudu  來源: 博客園  發布時間: 2011-03-10 17:35  閱讀: 12417 次  推薦: 7   原文鏈接   [收藏]  

  問題場景:

  在改進博客園博客后臺的過程中,有一個頁面我們想用ASP.NET MVC來寫。但我們不想通過設置<modules runAllManagedModulesForAllRequests="true"/>使用System.Web.Routing來處理請求,因為不能確定這是否會與我們現有的URL重寫產生沖突。我們只是想用Razor爽一下。

  解決思路:

  不改變ASP.NET管線的請求處理流程,請求還是正常到達一個.aspx頁面,然后再轉手給ASP.NET MVC。也就是把WebForm作為一個中轉站。

  好處:

  在現有項目中,以最小的代價用上ASP.NET MVC。先品嘗一下Razor的美味。

  解決方法:

  用System.Web.Mvc.MvcHandler可以輕松搞定,請看下面Home.aspx的代碼:

 
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected override void OnInit(EventArgs e)
{
System.Web.Routing.RequestContext requestContext
= new System.Web.Routing.RequestContext();
requestContext.HttpContext
= new HttpContextWrapper(Context);
requestContext.RouteData
= new System.Web.Routing.RouteData();
requestContext.RouteData.Values.Add(
"controller", "Home");
requestContext.RouteData.Values.Add(
"action", "Index");
IHttpHandler handler
= new System.Web.Mvc.MvcHandler(requestContext);
handler.ProcessRequest(Context);
}

</script>

  運行結果:

  項目結構:

  看,沒有Global.asax。

  演示代碼下載:

  CnblogsMvcDemo0305.rar

  更新:

  不走尋常路,是為了找到正確的路,感謝老趙指出了正確的路:

在Global.asax.cs的Application_Start中使用下面的代碼:

 
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute(

"Test.aspx",
"Test.aspx",
new { controller = "Test", action = "Index" }
);
7
0
 
標簽:WebForm MVC
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()