// should create a subdirectory ./bin and copy the assembly to it
static public WebHost Create(string name, string path)
{
if(!name.StartsWith(new string(Path.AltDirectorySeparatorChar, 1)))
{
name = Path.AltDirectorySeparatorChar + name;
}
webhost host = (webhost)applicationhost.createapplicationhost(
typeof(WebHost), name, path);
host.setvirtualdirectory(name);
host.setBaseDirectory(path);
return host;
}
但这样建立的程序有个bt的要求,他会在指定目录的bin子目录中去尝试载入宿主类型(webhost)的assembly,也就是说你必须把程序在bin子目录下复制一份,非常不爽。解决方法是自己手工完成整个建立过程,如下:
if(!physicaldir.endswith(new string(path.directoryseparatorchar, 1)))
{
physicalDir += Path.DirectorySeparatorChar;
}
appdomainsetup setup = new appdomainsetup();
setup.applicationname = "app_" + guid.newguid().tostring();
setup.ConfigurationFile = "web.config";
appdomain domain = appdomain.createdomain("asphost_" + guid.newguid().tostring(), null, setup);
domain.SetData(".appDomain", "*");
domain.SetData(".appPath", physicalDir);
domain.SetData(".appVPath", virtualDir);
domain.SetData(".domainId", domain.FriendlyName);
domain.SetData(".hostingVirtualPath", virtualDir);
domain.SetData(".hostingInstallDir", HttpRuntime.AspInstallDirectory);
webhost host = (webhost)domain.createinstanceandunwrap(
typeof(WebHost).Module.Assembly.FullName, typeof(WebHost).FullName);
host.setapplicationdomain(domain);
host.setVirtualDirectory(virtualDir);
host.setBaseDirectory(physicalDir);
return host;
}
这儿的一堆domain.setdata是传递参数给asp.net引擎。然后在那个appdomain中建立新的宿主类型的实例。这样就避免多份代码的尴尬。而使用asp.net就比较简单了,在宿主类中使用HttpRuntime.ProcessRequest函数处理特定请求。简单一点的话,可以直接用SimpleWorkerRequest包装请求,生成页面到一个指定的TextWriter中,如
public void requestpage(string page, string query, stream stream)
{
DoRequest(page, query, new StreamWriter(stream));
}
public void requestpage(string page, stream stream)
{
RequestPage(page, null, stream);
}
public string requestpage(string page, string query)
{
using(StringWriter writer = new StringWriter())
{
DoRequest(page, query, writer);
return writer.tostring();
}
}
public string requestpage(string page)
{
return RequestPage(page, string.Empty);
}
这个缺省的请求包装使用是简单,但对中文的兼容性不太好,过两天有空再自己写个强一点的吧,呵呵
最终类的使用就比较简单了,在winform程序中建立一个singleton模式的属性
public webhost.webhost host
{
get
{
if(_host == null)
{
_host = WebHost.WebHost.Create();
}
return _host;
}
}
然后请求指定的asp.net页面,如
html = host.requestpage(_page);
即可完成从动态的asp.net脚本到静态html的转换。嵌入winform程序中,还可以通过host类型完成两者之间的双向通讯,实现互相控制。下次有空继续,呵呵
参考资料:
1.Using the ASP.Net Runtime for extending desktop applications with dynamic HTML Scripts
http://www.west-wind.com/presentations/aspnetruntime/aspnetruntime.asp
2.executing asmx files without a web server http://radio.weblogs.com/0105476/stories/2002/10/24/executingAsmxFilesWithoutAWebServer.html
3.asp. net client-side hosting with cassini
http://msdn.microsoft.com/msdnmag/issues/03/01/CuttingEdge/
4.using asp.net runtime in desktop applications
http://www.codeguru.com/cs_internet/UsingAspRuntime.html