如何在没有托管的情况下启动ASP.Net应用程序?

3
我正在为我的ASP.Net Web应用程序编写集成测试,因此我希望在HTTP请求/响应级别上启动它并进行测试。 由于这些测试应该并发运行并具有最小权限,因此我不想将其暴露在任何真正的HTTP端口上。 我阅读到OWIN声称是ASP.Net应用程序和Web服务器之间的接口。 我有一个想法,即使用一些模拟Web服务器对象,该对象使用OWIN来托管ASP.Net应用程序,并且不会将其暴露在任何HTTP端口上。 而是,Web服务器对象应通过调用其方法接受HTTP请求,将其提供给其托管的应用程序,并将响应转发给调用者。 是否存在任何现有的解决方案?

1
你能否将IIS放在自己的服务器、台式机或笔记本电脑上?如果是这样,那么你可以在Visual Studio之外本地托管它。 - Simon Price
你不需要使用IIS或其他托管进程。你可以模拟一切,包括HTTP上下文。 - Dawid Rutkowski
@SimonPrice 是的。另一个选择是使用OWIN自托管。然而,这会导致性能下降,并且在并行运行多个测试的情况下会成为问题。 - stop-cran
@dawidr 我将执行端到端测试 - 从 HttpRequest 到 HttpResponse。我不是指单元测试。 - stop-cran
1
你正在使用.NET Core吗?如果是的话,请看这里:https://docs.asp.net/en/latest/testing/integration-testing.html - Dawid Rutkowski
显示剩余3条评论
2个回答

1
如果您正在使用.NET Core,那么在这里您将找到有用的信息:https://docs.asp.net/en/latest/testing/integration-testing.html 以下是一个示例,说明如何配置测试服务器:
public static void Main(string[] args)
{
     var contentRoot = Directory.GetCurrentDirectory();

     var config = new ConfigurationBuilder()
        .SetBasePath(contentRoot)
        .AddJsonFile("hosting.json", optional: true)
        .Build();

    //WebHostBuilder is required to build the server. We are configurion all of the properties on it
    var hostBuilder = new WebHostBuilder()

    //Server
    .UseKestrel()

    //URL's
    .UseUrls("http://localhost:6000")

    //Content root - in this example it will be our current directory
    .UseContentRoot(contentRoot)

    //Web root - by the default it's wwwroot but here is the place where you can change it
    //.UseWebRoot("wwwroot")

    //Startup
    .UseStartup<Startup>()

    //Environment
    .UseEnvironment("Development")

    //Configuration - here we are reading host settings form configuration, we can put some of the server
    //setting into hosting.json file and read them from there
    .UseConfiguration(config);

   //Build the host
   var host = hostBuilder.Build();

   //Let's start listening for requests
   host.Run();
}

正如您所看到的,您可以重复使用现有的 Startup.cs 类。


遇到了这个异常:"在 'FxPro.WebTrader.Middleware.Web.Startup' 类型中找不到名为 'ConfigureProduction' 或 'Configure' 的公共方法"。显然,UseStartup 适用于 Microsoft.AspNetCore.Builder.IApplicationBuilder 而不是 Owin.IAppBuilder - stop-cran
我的项目是基于ASP.Net MVC的,所以这种方法不能使用。不管怎样,你帮我找到了一个合适的选项(请看我的回答),非常感谢! - stop-cran

0

感谢dawidr,我找到了一种类似的方法,适用于使用ASP.Net MVC/Web API的人 - Microsoft.Owin.Testing

using (var server = TestServer.Create<Startup>())
    server.HttpClient.GetAsync("api/ControllerName")
        .Result.EnsureSuccessStatusCode();

通过这种方式,我们可以使用(和测试)Owin的Startup对象,在实际的托管环境中使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接