将Asp.net mvc整合进现有Asp.net webform项目
2009-11-03 16:44:32 来源:WEB开发网核心提示:本文将实现在asp.net webform中开发asp.net mvc,并部署在网络上的虚拟主机上首先在我们的项目中的bin目录下拷贝三个DLL文件,相信你已经知道是哪三个文件了1.System.Web.Mvc.dllpath:C:\PRogram Files\Microsoft ASP.NET\ASP.NET MVC
本文将实现在asp.net webform中开发asp.net mvc,并部署在网络上的虚拟主机上
首先在我们的项目中的bin目录下拷贝三个DLL文件,相信你已经知道是哪三个文件了
1.System.Web.Mvc.dll path:C:\PRogram Files\Microsoft ASP.NET\ASP.NET MVC 2.0\Assemblies
2.System.Web.Routing path:C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5
3.System.Web.Abstractions.dll path:同上
如果安装了.net 3.5 sp1 System.Web.Routing则可以不用拷贝
注意一定要引用这三个文件
但我们全部拷贝方便一点,我们先跳过创建global.asax,我们将现有项目做为View,那么我们需要创建
Controller和Model,我们创建的项目(类库)分别为Sonven.Compositeaspnetmvc.Controllers和
Sonven.CompositeAspNetMvc.Models,好了Asp.net mvc的文件组织就差不多了,现在开始配置,
最关键的是要在Web.Config里面添加一个模块
<system.web>
<httpModules>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule"/>
</httpModules>
</system.web>
最好加上System.Web.Routing程序集密匙,上面是个错误的示范,但这样也可以运行哈
我们现在在我们的项目中添加一个文件夹和View文件,如果你试图将所有的View都放在一个Views文件夹下的话可以略过
实现自己的视图引擎,视图引擎代码如下
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text.RegularExpressions;
namespace Sonven.CompositeAspNetMvc.ViewEngine
{
public class ViewEngine:VirtualPathProviderViewEngine
{
private static IList<string> _partialViewLocationFormats;
private static IList<string> _viewLocationFormats;
private static IList<string> _areaLocationFormats;
private bool isTrace;
static ViewEngine()
{
//初始化文件位置
_partialViewLocationFormats = new List<string>();
_viewLocationFormats = new List<string>();
_areaLocationFormats = new List<string>();
//Shared文件夹为存放公告usercontrol和masterpage的地方
_partialViewLocationFormats.Add("~/Shared/{0}.ascx");
ExploreDirectories(new DirectoryInfo(HttpContext.Current.Server.MapPath("~/")));
}
public ViewEngine()
{
this.MasterLocationFormats =new string[]{"~/{0}.master","~/{1}/{0}.master","~/masters/{0}.master"};
this.PartialViewLocationFormats = _partialViewLocationFormats.ToArray();
this.ViewLocationFormats = _viewLocationFormats.ToArray();
}
/// <summary>
/// 设置是否追踪显示相关信息
/// </summary>
public bool IsTrace {set { isTrace = value; } }
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return new WebFormView(partialPath);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
if (isTrace)
{
StringBuilder sb = new StringBuilder(500);
sb.Append("请求路径:" + viewPath + "<br />");
foreach (string routeformat in _viewLocationFormats)
{
if (Regex.IsMatch(viewPath, routeformat.Replace("{0}", "(\\w+)")))
sb.Append("<span style=\"color:red\">" + routeformat + "</span><br />");
else sb.Append(routeformat.ToString() + "<br />");
}
sb.Append("<span style=\"color:black\">+</span> 未监视View的文件夹包含字符:");
foreach (string nowatch in notWatchDirectories)
{
sb.Append(nowatch + ",");
}
HttpContext.Current.Response.Write("<div style=\"clear:both;border:solid 1px gold;background:#FEF8E0;" +
"padding:5px 20px;font-size:14px;font-family:Tahoma;line-height:22px;margin:2px 0;color:#696969;\">" + sb.ToString() +
"<br/><span style=\"color:silver\">注:红色表示匹配action路径,避免文件夹中存在同名view否则可能出现异常</span></div>");
}
return new WebFormView(viewPath, masterPath);
}
#region 添加匹配文件
private static DirectoryInfo[] dirs;
//获取根目录文件路径长度
private static readonly int bootPathLength = HttpContext.Current.Server.MapPath("~/").Length;
static void ExploreDirectories(DirectoryInfo dir)
{
RegisterViewPathFormats(dir.FullName);
dirs = dir.GetDirectories();
foreach (DirectoryInfo d in dirs)
{
ExploreDirectories(d);
}
}
private static string path;
//设置不监视的文件夹包含的字符
private static string[] notWatchDirectories = { "app", "bin","Scripts","js","images","style","files","obj","Properties" };
static void RegisterViewPathFormats(string filePath)
{
path = filePath.Substring(bootPathLength).Replace("\\", "/");
foreach (string directoryName in notWatchDirectories)
{
if (Regex.IsMatch(path, "(\\w*)" + directoryName + "(\\w*)", RegexOptions.IgnoreCase)) return;
}
if (path == "") return ;//防止 /
_partialViewLocationFormats.Add("~/" + path + "/{0}.ascx");
_partialViewLocationFormats.Add("~/" + path + "/usercontrols/{0}.ascx");
_viewLocationFormats.Add("~/" + path + "/{0}.aspx");
}
#endregion
/*
public void InsertViewLocation(string viewPath)
{
if (Regex.IsMatch(viewPath, @"~/(\w+)\{0\}\.aspx", RegexOptions.IgnoreCase))
_viewLocationFormats.Add(viewPath);
else throw new Exception("ViewLoction格式错误,必须以~/开头包含{0}占位符的aspx文件路径");
}
public void InsertPartialLocation(string partialPath)
{
if (Regex.IsMatch(partialPath, @"~/(\w+)\{0\}\.ascx", RegexOptions.IgnoreCase))
_partialViewLocationFormats.Add(partialPath);
else throw new Exception("PartialLoction格式错误,必须以~/开头包含{0}占位符ascx文件路径");
}*/
}
}
编译在sonven.ComposteAspnetMVC中的bin目录下的CompositeASpnetmvc.ViewEngine.dll
有了这个视图引擎可以不用把View放在一个Views文件夹下,不知道这样是不是错误的,但我比较喜欢自由的组织文件
接下来自己在Controllers项目中添加controller和在View中添加View,
完成了之后,我们最后来创建global.asax
其代码如下
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Sonven.CompositeAspNetMvc.ViewEngine;
namespace Sonven.CompositeAspNetMVC
{
public class Global : System.Web.Httpapplication
{
private void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
}
}
好了这下试试应该就可以了,但是我们将其部署到IIS发现访问如 /Home/Index会返回404 Error
解决办法如下
这下就可以了,但是当我们部署到网络上的虚拟主机上就遇到问题了,虚拟主机允许我们这样操作吗?
比较懂技术的虚拟主机技术员已经这样做了,但不幸的是很少会这样做的
那在虚拟主机上怎么用呢?答案是用asp.net能识别的扩展名,可以在路由上填加一些规则,其后缀为aspx
我们换另外一种,你只需要修改global.asax为如下代码:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Sonven.CompositeAspNetMvc.ViewEngine;
namespace Sonven.CompositeAspNetMVC
{
public class Global : System.Web.HttpApplication
{
private void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", //适用于虚拟主机,ext可以为ashx,aspx,ascx,asmx
"{controller}.{ext}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
routes.MapRoute(
"Default2", //适用可以设置IIS或IIS版本为7.0以上
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
}
}
你就可以用/home.aspx/Index这样的地址访问了,同时也可以用Home/Index(IIS经过配置)
您可以拷贝CompositeAspNetMvc.ViewEngine.dll在您的项目中并引用,对global.asax
的Application_Start方法中添加如下代码
ViewEngine engine = new ViewEngine();
engine.IsTrace =true; //是否显示请求信息,发布时候请删除此行
ViewEngines.Engines.Add(engine);
你将看到下面的结果,engine.IsTrace =false; 既可以取消请求的文件匹配信息
好了,你现在可以试试了.欢迎拍砖,指正错误
首先在我们的项目中的bin目录下拷贝三个DLL文件,相信你已经知道是哪三个文件了
1.System.Web.Mvc.dll path:C:\PRogram Files\Microsoft ASP.NET\ASP.NET MVC 2.0\Assemblies
2.System.Web.Routing path:C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5
3.System.Web.Abstractions.dll path:同上
如果安装了.net 3.5 sp1 System.Web.Routing则可以不用拷贝
注意一定要引用这三个文件
但我们全部拷贝方便一点,我们先跳过创建global.asax,我们将现有项目做为View,那么我们需要创建
Controller和Model,我们创建的项目(类库)分别为Sonven.Compositeaspnetmvc.Controllers和
Sonven.CompositeAspNetMvc.Models,好了Asp.net mvc的文件组织就差不多了,现在开始配置,
最关键的是要在Web.Config里面添加一个模块
<system.web>
<httpModules>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule"/>
</httpModules>
</system.web>
最好加上System.Web.Routing程序集密匙,上面是个错误的示范,但这样也可以运行哈
我们现在在我们的项目中添加一个文件夹和View文件,如果你试图将所有的View都放在一个Views文件夹下的话可以略过
实现自己的视图引擎,视图引擎代码如下
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text.RegularExpressions;
namespace Sonven.CompositeAspNetMvc.ViewEngine
{
public class ViewEngine:VirtualPathProviderViewEngine
{
private static IList<string> _partialViewLocationFormats;
private static IList<string> _viewLocationFormats;
private static IList<string> _areaLocationFormats;
private bool isTrace;
static ViewEngine()
{
//初始化文件位置
_partialViewLocationFormats = new List<string>();
_viewLocationFormats = new List<string>();
_areaLocationFormats = new List<string>();
//Shared文件夹为存放公告usercontrol和masterpage的地方
_partialViewLocationFormats.Add("~/Shared/{0}.ascx");
ExploreDirectories(new DirectoryInfo(HttpContext.Current.Server.MapPath("~/")));
}
public ViewEngine()
{
this.MasterLocationFormats =new string[]{"~/{0}.master","~/{1}/{0}.master","~/masters/{0}.master"};
this.PartialViewLocationFormats = _partialViewLocationFormats.ToArray();
this.ViewLocationFormats = _viewLocationFormats.ToArray();
}
/// <summary>
/// 设置是否追踪显示相关信息
/// </summary>
public bool IsTrace {set { isTrace = value; } }
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return new WebFormView(partialPath);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
if (isTrace)
{
StringBuilder sb = new StringBuilder(500);
sb.Append("请求路径:" + viewPath + "<br />");
foreach (string routeformat in _viewLocationFormats)
{
if (Regex.IsMatch(viewPath, routeformat.Replace("{0}", "(\\w+)")))
sb.Append("<span style=\"color:red\">" + routeformat + "</span><br />");
else sb.Append(routeformat.ToString() + "<br />");
}
sb.Append("<span style=\"color:black\">+</span> 未监视View的文件夹包含字符:");
foreach (string nowatch in notWatchDirectories)
{
sb.Append(nowatch + ",");
}
HttpContext.Current.Response.Write("<div style=\"clear:both;border:solid 1px gold;background:#FEF8E0;" +
"padding:5px 20px;font-size:14px;font-family:Tahoma;line-height:22px;margin:2px 0;color:#696969;\">" + sb.ToString() +
"<br/><span style=\"color:silver\">注:红色表示匹配action路径,避免文件夹中存在同名view否则可能出现异常</span></div>");
}
return new WebFormView(viewPath, masterPath);
}
#region 添加匹配文件
private static DirectoryInfo[] dirs;
//获取根目录文件路径长度
private static readonly int bootPathLength = HttpContext.Current.Server.MapPath("~/").Length;
static void ExploreDirectories(DirectoryInfo dir)
{
RegisterViewPathFormats(dir.FullName);
dirs = dir.GetDirectories();
foreach (DirectoryInfo d in dirs)
{
ExploreDirectories(d);
}
}
private static string path;
//设置不监视的文件夹包含的字符
private static string[] notWatchDirectories = { "app", "bin","Scripts","js","images","style","files","obj","Properties" };
static void RegisterViewPathFormats(string filePath)
{
path = filePath.Substring(bootPathLength).Replace("\\", "/");
foreach (string directoryName in notWatchDirectories)
{
if (Regex.IsMatch(path, "(\\w*)" + directoryName + "(\\w*)", RegexOptions.IgnoreCase)) return;
}
if (path == "") return ;//防止 /
_partialViewLocationFormats.Add("~/" + path + "/{0}.ascx");
_partialViewLocationFormats.Add("~/" + path + "/usercontrols/{0}.ascx");
_viewLocationFormats.Add("~/" + path + "/{0}.aspx");
}
#endregion
/*
public void InsertViewLocation(string viewPath)
{
if (Regex.IsMatch(viewPath, @"~/(\w+)\{0\}\.aspx", RegexOptions.IgnoreCase))
_viewLocationFormats.Add(viewPath);
else throw new Exception("ViewLoction格式错误,必须以~/开头包含{0}占位符的aspx文件路径");
}
public void InsertPartialLocation(string partialPath)
{
if (Regex.IsMatch(partialPath, @"~/(\w+)\{0\}\.ascx", RegexOptions.IgnoreCase))
_partialViewLocationFormats.Add(partialPath);
else throw new Exception("PartialLoction格式错误,必须以~/开头包含{0}占位符ascx文件路径");
}*/
}
}
编译在sonven.ComposteAspnetMVC中的bin目录下的CompositeASpnetmvc.ViewEngine.dll
有了这个视图引擎可以不用把View放在一个Views文件夹下,不知道这样是不是错误的,但我比较喜欢自由的组织文件
接下来自己在Controllers项目中添加controller和在View中添加View,
完成了之后,我们最后来创建global.asax
其代码如下
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Sonven.CompositeAspNetMvc.ViewEngine;
namespace Sonven.CompositeAspNetMVC
{
public class Global : System.Web.Httpapplication
{
private void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
}
}
好了这下试试应该就可以了,但是我们将其部署到IIS发现访问如 /Home/Index会返回404 Error
解决办法如下
这下就可以了,但是当我们部署到网络上的虚拟主机上就遇到问题了,虚拟主机允许我们这样操作吗?
比较懂技术的虚拟主机技术员已经这样做了,但不幸的是很少会这样做的
那在虚拟主机上怎么用呢?答案是用asp.net能识别的扩展名,可以在路由上填加一些规则,其后缀为aspx
我们换另外一种,你只需要修改global.asax为如下代码:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Sonven.CompositeAspNetMvc.ViewEngine;
namespace Sonven.CompositeAspNetMVC
{
public class Global : System.Web.HttpApplication
{
private void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", //适用于虚拟主机,ext可以为ashx,aspx,ascx,asmx
"{controller}.{ext}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
routes.MapRoute(
"Default2", //适用可以设置IIS或IIS版本为7.0以上
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
}
}
你就可以用/home.aspx/Index这样的地址访问了,同时也可以用Home/Index(IIS经过配置)
您可以拷贝CompositeAspNetMvc.ViewEngine.dll在您的项目中并引用,对global.asax
的Application_Start方法中添加如下代码
ViewEngine engine = new ViewEngine();
engine.IsTrace =true; //是否显示请求信息,发布时候请删除此行
ViewEngines.Engines.Add(engine);
你将看到下面的结果,engine.IsTrace =false; 既可以取消请求的文件匹配信息
好了,你现在可以试试了.欢迎拍砖,指正错误
- ››asp.net页面弄成伪静态页面
- ››Asp.net 中将汉字转换成拼音的方法
- ››ASP.NET及JS中的cookie基本用法
- ››ASP.NET获取MS SQL Server安装实例
- ››asp.net实现调用百度pai 在线翻译英文转中文
- ››ASP.NET页面选项进行提示判断
- ››Asp.net定时执行程序
- ››ASP.NET中利用DataList实现图片无缝滚动
- ››ASP.NET验证控件RequiredFieldValidator
- ››ASP.NET中使用System.Net.Mail发邮件
- ››ASP.NET中获取用户控件中控件的ID
- ››ASP.NET中FileBytes写成文件并存档
赞助商链接