I want to preprocess and postprocess all outgoing requests that are going from my Blazor client to Server API. The best solution is to add custom 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:
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.
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 example:
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:
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);