摘要:本想试一下能不能用PageParser.GetCompiledPageInstance方法来获得Asp.Net Page的实例,以便在用NUnit测试时能对Asp.Net页面有更多的控制,却发现了一个有意思的现象。 首先,为了不访问IIS,也能处理Asp.Net的Page,先要构造一个host出来,最简单的方法就是用ApplicationHost对象的CreateApplicationHost方法。public class MyHost static public MyHost Create(string virtualDir, string physicalDir){ MyHost host = (MyHost) ApplicationHost.CreateApplicationHost(    typeof(MyHost), virtualDir, physicalDir); host.PhysicalDir  = physicalDir; host.VirtualDir = virtualDir; return host;} CreateApplicationHost有个缺点就是需要将MyHost所在配件copy到web程序的bin目录下面 然后实现一个ProcessRequest方法来处理页面的请求public void ProcessRequest(string page,TextWriter writer) { HttpRuntime.ProcessRequest(new SimpleWorkerRequest(page, null, writer));} 获得Page的实例采用Hosting ASP.NET Outside of IIS介绍的方法,不过,作者提供的代码在if(AspNetNUnitHost.RUNTIME_INITIALIZED){ //This call has the side effect of initializing the HTTP runtime HttpRuntime.ProcessRequest(request); AspNetNUnitHost.RUNTIME_INITIALIZED = true;}处好像有点问题,应该是AspNetNUnitHost.RUNTIME_INITIALIZED==false才执行HttpRuntime.ProcessRequest(request)吧? 而且原来的代码在执行到GetCompiledPageInstance会有Exception抛出,Object reference not set to an instance of an objectSystem.Web.UI.Page.get_Server()  at ASP.Test_aspx..ctor() in c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files\testsystemhelper\f4d71d06\\7e3d5470\\i8to6hq0.0.cs:line  0 不管上面这些,debug时发现用自定义的Host执行Asp.Net Page和IIS执行的结果有出入比如<aspropDownList id="cacheList" runat="server" Width="200px"></aspropDownList>IIS执行的结果为<select name="cacheList" id="cacheList" style="width:200px;">。。。。。。</select> 而MyHost的结果为<select name="cacheList" id="cacheList">。。。。。。</select> 宽度等信息不见了,看来是否用自定义的Host执行asp.net页面还要再考虑。...[阅读全文]