是否可以向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()
中的方法
到目前为止,我已经尝试过:
TestServer
(没有用):// did not work:
var builder = new WebHostBuilder()
.UseStartup<CustomApi.Startup>()
.ConfigureServices(services =>
{
services
.AddHttpClient("")
.AddHttpMessageHandler<ExternalProxySslDowngradeSimulator>();
浏览Registering a custom HttpClientBuilder并不意味着该频道。
HttpClientFactoryOptions
(无效)以为我可以绑定自定义HttpClientFactoryOptions
并将自定义操作添加到code for TestServer
。但是TestServer并没有真正使用默认的Http Client Factory的这种方式。
TestServer
的设置(无效)在文档/源代码中浏览并没有发现任何地方可以钩住。有一个HttpClientFactoryOptions.HttpMessageHandlerBuilderActions
,但是我没有看到如何让我对TestServer的自定义HttpMessangeHandler
有所了解。使用。
答案 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;