如何在Blazor客户端中注册HttpClient处理程序



我想对从Blazor客户端到服务器API的所有传出请求进行预处理和后处理。最好的解决方案是添加自定义HttpMessageHandler。

处理程序代码:

public class NameOfMyHandler : DelegatingHandler
{
public NameOfMyHandler()
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Debug.WriteLine("Process request");
var response = await base.SendAsync(request, cancellationToken);
Debug.WriteLine("Process response");
return response;
}
}

客户端中的代码->程序.cs->Main:

builder.Services.AddScoped<NameOfMyHandler>();
builder.Services.AddHttpClient("ThisIsClientCustomName", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<NameOfMyHandler>();

但当我尝试这样做时,我得到了一个错误:

An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

但正如你在代码中看到的,我确实指定了BaseAddress,我相信它是正确的。

问题出在哪里?我做错了什么?

过了一段时间,我发现它需要的不仅仅是添加那个处理程序。也可以用CCD_ 2或纯CCD_。

AddHttpClient示例:

builder.Services.AddScoped<NameOfMyHandler>();
builder.Services.AddHttpClient("ThisIsClientCustomName", 
client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<NameOfMyHandler>();
// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("ThisIsClientCustomName"));

纯HttpClient

HttpMessageHandler httpMessageHandler = new NameOfMyHandler()
{
InnerHandler = new HttpClientHandler()
};
builder.Services.AddScoped<NameOfMyHandler>(sc => httpMessageHandler);
var httpClient = new HttpClient(httpMessageHandler)
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
};
builder.Services.AddScoped(sp => httpClient);

相关内容

  • 没有找到相关文章

最新更新