You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Net.Http;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
|
|
namespace HttpClientStudy.UnitTest
|
|
|
|
|
{
|
|
|
|
|
public class DelegatingHandlerTest
|
|
|
|
|
{
|
|
|
|
|
private readonly ITestOutputHelper _logger;
|
|
|
|
|
public DelegatingHandlerTest(ITestOutputHelper outputHelper)
|
|
|
|
|
{
|
|
|
|
|
_logger = outputHelper;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Test()
|
|
|
|
|
{
|
|
|
|
|
//构建管道
|
|
|
|
|
var handler = new HandlerA()
|
|
|
|
|
{
|
|
|
|
|
//相当于下一个中间件(管道)
|
|
|
|
|
InnerHandler = new HandlerB()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
HttpClient httpClient = new HttpClient(handler);
|
|
|
|
|
|
|
|
|
|
var sd = await httpClient.GetAsync("http://127.0.0.1");
|
|
|
|
|
var contentText = await sd.Content.ReadAsStringAsync();
|
|
|
|
|
|
|
|
|
|
_logger.WriteLine(contentText);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class HandlerB : DelegatingHandler
|
|
|
|
|
{
|
|
|
|
|
protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
InnerHandler = new SocketsHttpHandler() { };
|
|
|
|
|
|
|
|
|
|
//请求前业务
|
|
|
|
|
|
|
|
|
|
var response = await base.SendAsync(request, cancellationToken);
|
|
|
|
|
|
|
|
|
|
//响应后业务
|
|
|
|
|
|
|
|
|
|
return response;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class HandlerA : DelegatingHandler
|
|
|
|
|
{
|
|
|
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
//请求前业务
|
|
|
|
|
|
|
|
|
|
var response = await base.SendAsync(request, cancellationToken);
|
|
|
|
|
|
|
|
|
|
//响应后业务
|
|
|
|
|
|
|
|
|
|
return response;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|