简体   繁体   English

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

[英]How to register HttpClient Handler in Blazor Client?

I want to preprocess and postprocess all outgoing requests that are going from my Blazor client to Server API.我想预处理和后处理从 Blazor 客户端到服务器 API 的所有传出请求。 The best solution is to add custom HttpMessageHandler.最好的解决方案是添加自定义 HttpMessageHandler。

Handler code:处理程序代码:

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;
    }
}

Code in Client->Program.cs->Main: Client->Program.cs->Main 中的代码:

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

But when I try to do so I get an error:但是当我尝试这样做时,我收到一个错误:

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

but as you can see in the code I do specify the BaseAddress and I am sure it is correct.但是正如您在代码中看到的,我确实指定了BaseAddress并且我确定它是正确的。

Where is the problem ?问题出在哪儿 ? What am I doing wrong ?我究竟做错了什么 ?

After some time I found out it requires more than adding that handler.一段时间后,我发现它需要的不仅仅是添加该处理程序。 And also it is possible to do it with AddHttpClient or pure HttpClient .也可以使用AddHttpClient或纯HttpClient来做到这AddHttpClient

AddHttpClient example:添加HttpClient示例:

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"));

or或者

Pure HttpClient :纯 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM