在 ASP.NET MVC 项目中使用 WebForm 比眉伴天荒 2022-01-11 23:31 270阅读 0赞 ASP.NET MVC和WebForm各有各的优点,我们可能需要同时使用ASP.NET MVC和WebForm。本文介绍了如何在ASP.NET MVC项目中使用WebForm。 首先新建一个名为WebForms的文件夹用于存放WebForm,并添加一个Web窗体文件Demo.aspx作为演示。 ![1.jpg][] Demo.aspx就简单的输出一句话“It’s a WebForm.” 关键步骤在于路由设置。如果你希望WebForms这个文件夹名作为URL的一部分,也就是普通WebForm应用程序的方式来访问这个Demo.aspx,那么只需要简单的忽略这个路由规则即可。 在Global.asax.cs文件的RegisterRoutes方法中加入以下代码 在Global.asax.cs文件的RegisterRoutes方法中加入以下代码 // 忽略对 WebForms 路径的路由 routes.IgnoreRoute("WebForms/\{weform\}"); 结果: 如果希望URL更友好或者不出现WebForms这个文件夹名,那就要自己写一个类继承IRouteHandler。 1publicclass WebFormsRouteHandler:IRouteHandler 2\{ 3privatestring pageName = string.Empty; 4 5public IHttpHandler GetHttpHandler(RequestContextrequestContext) 6\{ 7// 从URL中获取page参数 8pageName = requestContext.RouteData.GetRequiredString("page"); 9 10// 创建实例 11 // 根据 page 参数拼接成类似/WebForms/page.aspx地址来访问WebForms页面 12IHttpHandler hander = BuildManager.CreateInstanceFromVirtualPath("/WebForms/" \+ this.pageName+".aspx", typeof(System.Web.UI.Page)) as IHttpHandler; 13 14return 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都会匹配到这个路 [1.jpg]: /images/20220110/93ee7d03883e4847a6a34512e8789805.png
还没有评论,来说两句吧...