如何使用C#以编程方式运行ASP.Net开发服务器?

时间:2020-03-05 18:51:39  来源:igfitidea点击:

我有要构建自动化测试的ASP.NET网页(使用WatiN和MBUnit)。如何从我的代码启动ASP.Net开发服务器?我不想使用IIS。

解决方案

回答

据我所知,我们可以使用以下路径/语法从命令提示符启动开发服务器:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]

...所以我可以想象我们可以轻松地使用Process.Start()通过一些代码启动所需的细节。

自然地,我们需要将该版本号调整为最新/所需的版本号。

回答

这是我使用的工作原理:

using System;
using System.Diagnostics;
using System.Web;
...

// settings
string PortNumber = "1162"; // arbitrary unused port #
string LocalHostUrl = string.Format("http://localhost:{0}", PortNumber);
string PhysicalPath = Environment.CurrentDirectory //  the path of compiled web app
string VirtualPath = "";
string RootUrl = LocalHostUrl + VirtualPath;                 

// create a new process to start the ASP.NET Development Server
Process process = new Process();

/// configure the web server
process.StartInfo.FileName = HttpRuntime.ClrInstallDirectory + "WebDev.WebServer.exe";
process.StartInfo.Arguments = string.Format("/port:{0} /path:\"{1}\" /virtual:\"{2}\"", PortNumber, PhysicalPath, VirtualPath);
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;

// start the web server
process.Start();

// rest of code...