Globally apply SetBrowserRequestCredentials

Viewed 236

Is there any way to apply the Microsoft.AspNetCore.Components.WebAssembly.Http extension method SetBrowserRequestCredentials(BrowserRequestCredentials.Include) globally rather than having to do it on every individual request?

I'd like to avoid doing this on every call:

var request = new HttpRequestMessage(HttpMethod.Get, uri)
     .SetBrowserRequestCredentials(BrowserRequestCredentials.Include);

var response = await httpClient.SendAsync(request);

and simply have something like this:

var response = await httpClient.GetAsync(uri);
2 Answers

If you don't mind the request not being immutable, you can always create an extension method:

private static Task<HttpResponseMessage> SendAuthorisedAsync(this HttpClient client, HttpRequestMessage message)
{
    return client.SendAsync(message.SetBrowserRequestCredentials(BrowserRequestCredentials.Include));
}

Found this to be a simple solution in .NET 6.

builder.Services.AddHttpClient(Options.DefaultName, client =>
{
    // setup client
}).AddHttpMessageHandler<CredentialsMessageHandler>();

with the following middleware:

public class CredentialsMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);

        return base.SendAsync(request, cancellationToken);
    }
}
Related