How can I programmatically run the ASP.Net Development Server using C#?

前端 未结 4 2000
傲寒
傲寒 2021-02-04 11:41

I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use I

4条回答
  •  攒了一身酷
    2021-02-04 11:54

    Building upon @Ray Vega's useful answer, and @James McLachlan's important update for VS2010, here is my implementation to cover VS2012 and fallback to VS2010 if necessary. I also chose not to select only on Environment.Is64BitOperatingSystem because it went awry on my system. That is, I have a 64-bit system but the web server was in the 32-bit folder. My code therefore looks first for the 64-bit folder and falls back to the 32-bit one if necessary.

    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
        {
            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));
    }
    

    I am hoping that an informed reader might be able to supply the appropriate incantation for VS2013, as it apparently uses yet a different scheme...

提交回复
热议问题