在 ASP.NET MVC 项目中使用 WebForm 【转】

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。

public class WebFormsRouteHandler:IRouteHandler
{
    
private string pageName = string.Empty;

    
public WebFormsRouteHandler(string page)
    
{
        
this.pageName = page;
    }



    
public IHttpHandler GetHttpHandler(RequestContext requestContext)
    
{
        
// 创建实例
        IHttpHandler hander = BuildManager.CreateInstanceFromVirtualPath("/WebForms/" + this.pageName, typeof(System.Web.UI.Page)) as IHttpHandler;

        
return hander;
    }


}

然后在Global.asax.cs文件中加上新的路由规则

routes.Add("webforms"new Route("web/demo"new WebFormsRouteHandler("demo.aspx")));

当路径匹配web/demo时用自定义的类来处理这个请求。
结果(URL改变):

原文地址:https://www.cnblogs.com/cxd4321/p/1569619.html