简体   繁体   English

使用Asp.NetCore TestServer托管的WebAPI的HttpClient连接问题

[英]HttpClient connection issue to WebAPI hosted using Asp.NetCore TestServer

In the unit Test cases, TestServer is used for in-memory hosting of the WebAPI. 在单元测试用例中, TestServer用于WebAPI的内存中托管。 After this, we are trying to make HttpConnection to this hosted WebAPI using some code like this: 在此之后,我们尝试使用以下代码为此托管的WebAPI创建HttpConnection

HttpClient client= new HttpClient();
client.BaseAddress("url");
client.GetAsync("url").Result();

This code gives an exception, with the error message 此代码提供异常,并显示错误消息

"Connection refused". “拒绝连接”。

But if we get the HttpClient object using the below code and follow the above steps, it works fine. 但是如果我们使用下面的代码获得HttpClient对象并按照上面的步骤操作,那么它可以正常工作。

TestServer.CreateClient() 

What could be the reason behind it? 它背后的原因是什么? Is it because it's an in-memory hosted WebAPI? 是因为它是内存托管的WebAPI吗? No actual Http context is there?? 没有实际的Http上下文?

That's by design. 这是设计的。 When you call TestServer.CreateClient() a client with special HttpMessageHandler is created. 当您调用TestServer.CreateClient() ,会创建一个具有特殊 HttpMessageHandler的客户端。 That handler allows to directly call APIs under test without exposing it as HTTP server: 该处理程序允许直接调用测试中的API而不将其作为HTTP服务器公开:

public class TestServer : IServer, IDisposable
{
    public HttpClient CreateClient()
    {
        HttpClient httpClient = new HttpClient(this.CreateHandler());
        ...
    }
}

That should be faster and suitable enough for unit-testing. 这应该更快,更适合单元测试。 For integration testing, run a Kestrel server at test startup. 对于集成测试,请在测试启动时运行Kestrel服务器。

PS I hope your application design became better with DI instead of explicit building. PS我希望您的应用程序设计通过DI而不是显式构建变得更好。 That's nice you resolved the problem this way. 你用这种方式解决问题很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM