使用 refit 您可以实现 DelegatingHandler 然后注册它以在发送之前对 http 请求执行任何您需要的操作。这是为每个请求添加一个原始标头。改装界面无需担心。
public class AddOriginHeaderToRequest : DelegatingHandler
{
private const string ServiceNameSettingLocation = "AppConfig:Logging:ServiceName";
private readonly IHttpContextAccessor httpContextAccessor;
private readonly IConfiguration configuration;
public AddOriginHeaderToRequest(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
{
this.httpContextAccessor = httpContextAccessor;
this.configuration = configuration;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var origin = this.configuration[AddOriginHeaderToRequest.SomethingThatShouldBeDefined];
if (!(request.Headers.Contains("origin") || request.Headers.Contains("Origin")) && origin != null)
{
request.Headers.Add("origin", origin);
}
return await base.SendAsync(request, cancellationToken);
}
}
然后像这样注册它:
services.AddTransient<AddOriginHeaderToRequest>();
然后可以像这样注册改装客户端(这是我们的一个 nuget 包的修订版本,因此希望能够了解它是如何工作的):
public static IHttpClientBuilder AddHttpClientWithDefaultHandlers(
this IServiceCollection services,
string name,
Action<HttpClient> configureClient)
{
return services.AddHttpClient(name, configureClient)
.AddHttpMessageHandler<AddOriginHeaderToRequest>();
}
然后在我们的服务中,我们像这样注册我们的改装处理程序:
services.AddHttpClientWithRefitAndDefaultHandlers<ImyHttpClient>(
"myHttpClient",
c =>
{
c.BaseAddress = new Uri(appSettings.Value.AppConfig.SomeUrl);
});
这可以简化,但我们有许多不同的处理程序以标准方式处理我们的 http 请求。
我希望这能给你一个关于它如何工作的指导。