Reputation: 51
I need help with the below code for a WPF .net core 3.1 app which uses Refit for handing REST APIs. I am trying to get the value of the AuthToken from the response header. But I can't find a property holds the value of the AuthorizationHeaderValueGetter.
I do see some bugs related to this issue - https://github.com/reactiveui/refit/issues/689. It is claimed to have been fixed in the .net core 3.1 version. But I haven't been able to retrieve the response header yet.
App.xaml.cs
private void ConfigureServices(IConfiguration configuration, IServiceCollection services)
{
services.AddRefitClient<IService>(new RefitSettings()
{
AuthorizationHeaderValueGetter = () => Task.FromResult("AuthToken")
})
.ConfigureHttpClient(c => c.BaseAddress = new
Uri(Configuration.GetSection("MyConfig:GatewayService").Value));
}
IService.cs The Interface IService has been defined as follows:
[Headers("Content-Type: application/json")]
public interface IService
{
[Post("/v1/Authtoken/")]
public Task<string> Authenticate([Body] Authenticate payload);
}
I am Injecting IService in my ViewModel (WPF) and trying to get the the value of the "AuthToken" header which should have been set.
Viewmodel
public class SomeViewModel: ISomeViewModel
{
public SomeViewModel(IService service)
{
this.Service = service;
}
public async Task<Tuple<bool, string>> Somemethod()
{
var authResponse = await Service.Authenticate(authPayload);
.......
}
}
Upvotes: 2
Views: 7426
Reputation: 51
I managed to get the response header. The return type of the service has to be changed to System.Net.Http.HttpResponseMessage.
[Headers("Content-Type: application/json")]
public interface IService
{
[Post("/v1/Authtoken/")]
public Task<HttpResponseMessage> Authenticate([Body] Authenticate payload);
}
Created an extension method which looks up the response headers to get the "AuthToken" value.
public static class RefitExtensions
{
public static async Task<string>GetAuthToken(this Task<HttpResponseMessage> task)
{
var response = await task.ConfigureAwait(false);
string authToken = response.Headers.GetValues("AuthToken").FirstOrDefault();
return await Task.FromResult(authToken);
}
}
In the view model, I got the authtoken value with the following statement.
var authToken = await Service.Authenticate(authPayload).GetAuthToken();
Upvotes: 3