zoukankan      html  css  js  c++  java
  • 一起谈.NET技术,不走寻常路:在WebForm中使用MVC 狼人:

      问题场景:

      在改进博客园博客后台的过程中,有一个页面我们想用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" }
    );
  • 相关阅读:
    HDOJ1267 下沙的沙子2[DP或卡特兰数]
    HDOJ1711 Number Sequence[KMP模版]
    HDOJ2546 饭卡[DP01背包问题]
    寻找必败态——一类博弈问题的快速解法
    kmp 模版
    网络流题目
    HDOJ1261 字串数[组合+大数]
    传说中效率最高的最大流算法(Dinic) [转]
    ACM博弈论
    HDOJ1061 Rightmost Digit[简单数学题]
  • 原文地址:https://www.cnblogs.com/waw/p/2162933.html
Copyright © 2011-2022 走看看