I'm moving some code from .net framework to .net standard and i'm struggling to replicate some code that creates a HttpClient.
private HttpClient CreateHttpClient(Guid userId, SiteHandler siteHandler)
{
List<DelegatingHandler> handlers = new List<DelegatingHandler>
{
new AccessTokenHandler(_authorisationService, userId)
};
HttpClient client = HttpClientFactory.Create(handlers.ToArray());
client.BaseAddress = _baseAddressUri;
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
public class AccessTokenHandler : DelegatingHandler
{
private readonly IAuthorisationService _authorisationService;
private readonly Guid _userId;
public AccessTokenHandler(IAuthorisationService authorisationService, Guid userId)
{
_authorisationService = authorisationService ?? throw new ArgumentNullException(nameof(authorisationService));
_userId = userId;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string token = await _authorisationService.GetValidTokenAsync(_userId);
if (token == null)
{
throw new ApiTokenException();
}
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await base.SendAsync(request, cancellationToken);
}
}
What this code does is it sets up some middleware on the request so that when a request is made using the HttpClient the AccessTokenHandler adds an Access Token for the user to the request at the time of the call.
I can't seem to find anything that allows me to do this using .net standard. I can't find HttpClientFactory outside of a .net framework project.
Can anyone help?