将委派处理程序(发出请求的中间件)添加到TestServer的HttpClient

时间:2019-08-04 11:58:11

标签: c# testing asp.net-core .net-core dotnet-httpclient

是否可以向asp.net核心DelegationHandler构建的HttpClient中添加自定义TestServer(发出请求的中间件)?

我正在尝试结合使用HttpClientFactory来影响HttpClients的{​​{3}}与内存中测试实用程序customization possibilities

public class ExternalProxySslDowngradeSimulator : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken token)
     {
        if (request.RequestUri.Scheme == "https")
                request.RequestUri = new Uri(
                     request.RequestUri.OriginalString.Replace("https:", "http:"));

         return base.SendAsync(request, token);
     }
}

[TestFixture
public class TestClass
{
   [Test]
   public async Task CallApi()
   {
      var builder = new WebHostBuilder()
           .ConfigureAppConfiguration((ctx, config) => { })
           .UseUrl("http://customDomain.com")
           .UseStartup<CustomApi.Startup>();

      var testServer = new Microsoft.AspNetCore.TestHost.TestServer(builder);

      var httpClient = testServer.CreateClient();

      var apiResult = await httpClient.GetAsync("https://customDomain");
   }
}

我找不到将DelegatingHandler插入从HttpClient返回的testServer.CreateClient()中的方法


到目前为止,我已经尝试过:

  1. TestServer(没有用):
// did not work:
var builder = new WebHostBuilder()
   .UseStartup<CustomApi.Startup>()
   .ConfigureServices(services =>
   {
        services
          .AddHttpClient("")
          .AddHttpMessageHandler<ExternalProxySslDowngradeSimulator>();

浏览Registering a custom HttpClientBuilder并不意味着该频道。

  1. 自定义HttpClientFactoryOptions(无效)

以为我可以绑定自定义HttpClientFactoryOptions并将自定义操作添加到code for TestServer。但是TestServer并没有真正使用默认的Http Client Factory的这种方式。

  1. 自定义TestServer的设置(无效)

在文档/源代码中浏览并没有发现任何地方可以钩住。有一个HttpClientFactoryOptions.HttpMessageHandlerBuilderActions,但是我没有看到如何让我对TestServer的自定义HttpMessangeHandler有所了解。使用。

1 个答案:

答案 0 :(得分:1)

因此,您要做的是使用测试服务器(代码示例中的服务器)的CreateHandler方法和HttpClientFactory.Create方法创建自己的客户端。

var client = HttpClientFactory.Create(Server.CreateHandler(), new CustomDelegate() );
client.BaseAddress = Server.BaseAddress;

这使我永远想不通。希望这对您有帮助。

所以您的示例将是

var httpClient = HttpClientFactory.Create(testServer.CreateHander(), new ExternalProxySslDowngradeSimulator());
httpClient.BaseAddress = testServer.BaseAddress;