HttpClient dotnet核心根据请求添加授权令牌

时间:2017-09-15 10:22:04

标签: c# .net-core dotnet-httpclient

我将.net框架中的一些代码移动到.net标准,并且我正在努力复制一些创建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);
    }
}

此代码的作用是在请求中设置一些中间件,以便在使用HttpClient发出请求时,AccessTokenHandler会在调用时为用户添加访问令牌。

我似乎无法找到允许我使用.net标准执行此操作的任何内容。我无法在.net框架项目之外找到HttpClientFactory。

有人可以帮忙吗?

0 个答案:

没有答案