2

我正在尝试使用“ConfigurePrimaryHttpMessageHandler”将处理程序附加到 httpclientfactory

但是当我查看 HttpClient 内部以查看处理程序是否存在时,我找不到它

我是否正确连接了处理程序?

任何建议

     services.AddHttpClient<IGitHubClient,GitHubClient>(client =>
            {
                client.BaseAddress = new Uri(myUri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            })
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
            {
                AllowAutoRedirect = false,
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
            });


    public interface IGitHubClient
    {
        Task<string> GetData();
    }

    public class GitHubClient : IGitHubClient
    {
        private readonly HttpClient _client;

        public GitHubClient(HttpClient httpClient)
        {
            _client = httpClient;
        }

        public async Task<string> GetData()
        {
            return await _client.GetStringAsync("/");
        }
    }

    public class ValuesController : Controller
    {
        private readonly IGitHubClient _gitHubClient;;

        public ValuesController(IGitHubClient gitHubClient)
        {
            _gitHubClient = gitHubClient;
        }

        [HttpGet]
        public async Task<ActionResult> Get()
        {
            //my _gitHubClient has no Handler attached!!!

            string result = await _gitHubClient.GetData();
            return Ok(result);
        }
    }
4

1 回答 1

2

您显示的代码是推荐的方法。

关于评论_gitHubClient

//我的 _gitHubClient 没有附加处理程序!!!

好像是个误会。

_gitHubClient是您在其实现中包装HttpClient实例的抽象。GitHubClient

public class GitHubClient : IGitHubClient {
    private readonly HttpClient _client; //<< Handler will be attached to this instance

    public GitHubClient(HttpClient httpClient) {
        _client = httpClient;
    }

    public async Task<string> GetData() {
        return await _client.GetStringAsync("/");
    }
}

正是那个包装的实例将具有附加的处理程序。

根据当前配置,每当框架必须创建IGitHubClient派生GitHubClient的注入实例时,工厂将HttpClient使用启动时提供的设置创建一个。其中还包括添加HttpClientHandlerConfigurePrimaryHttpMessageHandler

于 2018-06-26T13:56:33.243 回答