HttpClient的多种实现

时间:2018-10-15 09:39:14

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

场景:

  

我需要通过他们的REST API从两个项目管理系统(VSTS和Jira)中加载工作项。它们每个都有不同的授权机制:

     
      
  • VSTS:使用从数据库加载的访问令牌,具体取决于团队/用户组
  •   
  • Jira:使用从用户声明加载的个人令牌,具体取决于用户
  •   

基本类和接口:

public interface IProjectManagementClient
{
    ProjectManagementType Type { get; }
    Task<WorkItem> GetWorkItemAsync(ProjectManagement projectManagement, int id, CancellationToken token = default(CancellationToken));
    Task<List<WorkItem>> GetAllWorkItemsAsync(ProjectManagement projectManagement, string term, int limit = 10, CancellationToken token = default(CancellationToken));
}

public enum ProjectManagementType
{
    VSTS,
    Jira
}

public class ProjectManagement
{
    public int Id { get; set; }
    public ProjectManagementType Type { get; set; }
    public string BaseAddress { get; set; }
    public string AccessToken { get; set; }
}

设置:

services.AddHttpClient<IProjectManagementClient, VstsClient>();
services.AddHttpClient<IProjectManagementClient, JiraClient>()
    .AddHttpMessageHandler(provider => new BasicAuthHandler(provider.GetService<IHttpContextAccessor>(), CustomClaimTypes.TrackerToken));

用法示例:

public TimesheetsController(IEnumerable<IProjectManagementClient> projectManagementClients)
{
    _projectManagementClients = projectManagementClients;
}

public void DoWork()
{
    foreach (var timesheet in _timesheets)
    {
        var projectManagementClient = _projectManagementClients.First(o => o.Type == timesheet.ProjectManagement.Type);
        timesheet.WorkItem = timesheet.WorkItemId.HasValue
            ? await projectManagementClient.GetWorkItemAsync(timesheet.ProjectManagement, timesheet.WorkItemId.Value, token)
            : null;
    }
}

问题:

  

即使我仅将BasicAuthHandler注册到JiraClient。它已应用于VSTS和Jira客户端。

     

因此,它已覆盖了先前在VstsClient中设置的VSTS授权。

如果我一次只设置和使用它们,两者都可以正常工作。请帮忙。

1 个答案:

答案 0 :(得分:2)

JiraClientVstsClient覆盖,因为它们都以相同(空)名称注册,这是默认名称。尝试使用命名注册:

services.AddHttpClient<IProjectManagementClient, VstsClient>("VSTS");
services.AddHttpClient<IProjectManagementClient, JiraClient>("JIRA")
    .AddHttpMessageHandler(provider => new BasicAuthHandler(
        provider.GetService<IHttpContextAccessor>(),
        CustomClaimTypes.TrackerToken));

在这种情况下,IEnumerable<IProjectManagementClient>应该提供两项配置相同的项目,而不能覆盖。