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方法中加入以下代码
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
结果:
如果希望URL更友好或者不出现WebForms这个文件夹名,那就要自己写一个类继承IRouteHandler。
1
public class WebFormsRouteHandler:IRouteHandler
2
{
3
private string pageName = string.Empty;
4![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
public IHttpHandler GetHttpHandler(RequestContext requestContext)
6
{
7
// 从URL中获取page参数
8
pageName = requestContext.RouteData.GetRequiredString("page");
9![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
// 创建实例
11
// 根据 page 参数拼接成类似/WebForms/page.aspx地址来访问WebForms页面
12
IHttpHandler hander = BuildManager.CreateInstanceFromVirtualPath("/WebForms/" + this.pageName+".aspx", typeof(System.Web.UI.Page)) as IHttpHandler;
13![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
14
return hander;
15
}
16![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
17
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
11
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
12
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
13
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
14
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
15
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
16
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
17
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
然后在Global.asax.cs文件中加上新的路由规则
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
当路径匹配web/{page}时用自定义的类来处理这个请求,如web/demo或web/demo1等URL都会匹配到这个路由
本文适用于 ASP.NET MVC 1.0