1

I'm trying to set a HttpMessageHandler for a refit client which adds the Authorization Header to the request, but it's not working after I followed the documentation and multiple github examples.

Here is how I configure it:

 services.TryAddTransient<AuthorizationHeaderHandler>();

 services.AddRefitClient<IWebApi>()
                .ConfigureHttpClient(c => c.BaseAddress = new Uri(Configuration.GetSection("Apis:MyApi:Url").Value))
                .AddHttpMessageHandler<AuthorizationHeaderHandler>();

When I use this in the service layer, it gets resolved, but when I try to use it, it doesn't attach any Authorization header. Any thoughts ?

Radu Olteanu
  • 393
  • 4
  • 17
  • Here is a [link](https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient) to set Authorization Header of HttpClient.`thd` says `httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");` – Yiyi You Aug 06 '20 at 10:01

1 Answers1

0

I had a requirement for something similarl adding basic auth.. this worked for me:

var baseAuthHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}: 
   {password}"));

var refitSettings = new RefitSettings
{
   AuthorizationHeaderValueGetter = () => Task.FromResult(baseAuthHeader),                
};

services.AddRefitClient(typeof(IWebApi), refitSettings)
  .ConfigureHttpClient(config => config.BaseAddress = ...etc
  ....
Jayhova
  • 43
  • 4