我有 ASP.NET 网页,我想为其构建自动化测试(使用 WatiN 和 MBUnit)。如何从我的代码启动 ASP.Net 开发服务器?我不想使用 IIS。
4 回答
这就是我使用的有效方法:
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...
据我所知,您可以使用以下路径/语法从命令提示符启动开发服务器:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]
...所以我可以想象你可以很容易地使用 Process.Start() 通过一些代码来启动你需要的细节。
自然,您会希望将该版本号调整为您最近/想要的任何版本。
在@Ray Vega 的有用答案和@James McLachlan 对VS2010 的重要更新的基础上,这是我的实现,以涵盖VS2012 并在必要时回退到VS2010。我还选择不只在 Environment.Is64BitOperatingSystem 上选择,因为它在我的系统上出错了。也就是说,我有一个 64 位系统,但 Web 服务器位于 32 位文件夹中。因此,我的代码首先查找 64 位文件夹,并在必要时回退到 32 位文件夹。
public void LaunchWebServer(string appWebDir)
{
var PortNumber = "1162"; // arbitrary unused port #
var LocalHostUrl = string.Format("http://localhost:{0}", PortNumber);
var VirtualPath = "/";
var exePath = FindLatestWebServer();
var process = new Process
{
StartInfo =
{
FileName = exePath,
Arguments = string.Format(
"/port:{0} /nodirlist /path:\"{1}\" /virtual:\"{2}\"",
PortNumber, appWebDir, VirtualPath),
CreateNoWindow = true,
UseShellExecute = false
}
};
process.Start();
}
private string FindLatestWebServer()
{
var exeCandidates = new List<string>
{
BuildCandidatePaths(11, true), // vs2012
BuildCandidatePaths(11, false),
BuildCandidatePaths(10, true), // vs2010
BuildCandidatePaths(10, false)
};
return exeCandidates.Where(f => File.Exists(f)).FirstOrDefault();
}
private string BuildCandidatePaths(int versionNumber, bool isX64)
{
return Path.Combine(
Environment.GetFolderPath(isX64
? Environment.SpecialFolder.CommonProgramFiles
: Environment.SpecialFolder.CommonProgramFilesX86),
string.Format(
@"microsoft shared\DevServer\{0}.0\WebDev.WebServer40.EXE",
versionNumber));
}
我希望有见识的读者能够为 VS2013 提供适当的咒语,因为它显然使用了不同的方案......
You can easily use Process Explorer to find complete command line options needed for manually start it. Start Process Explorer while debugging your website. For VS2012, expand 'devenv.exe' node. Right-click on 'WebDev.WebServer20.exe' and from there you can see Path and Command Line values.