MVC与Webform混合开发
在实际项目中我们会想到用Asp.net MVC 做前台,WebForm做后台。既有性能又有开发效率。在MVC中实现两者混合开发也很容易。
我们这里介绍两种方:
第一种:设置路由忽略对WebForm的.aspx文件的控制访问
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
"Account",
"Account/{action}",
new { controller = "LoinAccount", action = "Index" }
);
routes.MapRoute(
"ads",
"Ads/{action}/{id}/{num}",
new { controller = "Ads", action = "ListAd" },
new { num = @"\d+" }
);
routes.MapRoute(
"News",
"News/Get_{newsId}/{year}/{month}/{day}.htm",
new { controller = "News", action = "Index" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
第二种:自已实现一个RouteHandler
/// <summary>
/// 对WebForms文件夹的路径处理
/// </summary>
public class WebFormsRouteHandler : IRouteHandler
{
private string _pageName = string.Empty;
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
// 从URL中获取page参数
_pageName = requestContext.RouteData.GetRequiredString("page");
IHttpHandler hander = BuildManager.CreateInstanceFromVirtualPath("/WebForms/" + this._pageName + ".aspx", typeof(System.Web.UI.Page)) as IHttpHandler;
return hander;
}
}
/// <summary>
/// 对WebForms里的子文件夹路径处理
/// </summary>
public class WebFormsFolderRouteHandler : IRouteHandler
{
private string _folderName = string.Empty;
private string _pageName = string.Empty;
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
// 从URL中获取folder参数
_folderName = requestContext.RouteData.GetRequiredString("folder");
// 从URL中获取page参数
_pageName = requestContext.RouteData.GetRequiredString("page");
IHttpHandler hander;
// 创建实例
// 根据folder 和 page 参数拼接成类似/WebForms/folder/page.aspx地址来访问WebForms页面
hander = BuildManager.CreateInstanceFromVirtualPath("/WebForms/" + this._folderName + "/" + this._pageName + ".aspx", typeof(System.Web.UI.Page)) as IHttpHandler;
return hander;
}
}
接下来新建WebForms文件夹,在其文件夹或子文件夹里添加aspx页面
最后再设置路由
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// 添加一个用WebFormsRouteHandler进行处理的路由
// 其中URL中{page}所占的部分会被在WebFormsRouteHandler中当做参数使用
routes.Add(new Route("web/{page}", new WebFormsRouteHandler()));
// 其中URL中{folder}和{page}所占的部分会被在WebFormsRouteHandler中当做参数使用
routes.Add(new Route("web/{folder}/{page}", new WebFormsFolderRouteHandler()));
routes.MapRoute(
"Account",
"Account/{action}",
new { controller = "LoinAccount", action = "Index" }
);
routes.MapRoute(
"ads",
"Ads/{action}/{id}/{num}",
new { controller = "Ads", action = "ListAd" },
new { num = @"\d+" }
);
routes.MapRoute(
"News",
"News/Get_{newsId}/{year}/{month}/{day}.htm",
new { controller = "News", action = "Index" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
这样就行了,如果觉得URL不够漂亮还可以修改路由里的路径让URL好看点。