Attaching httpHandler to httpclientFactory webapi aspnetcore 2.1

僤鯓⒐⒋嵵緔 提交于 2020-02-02 12:14:08

问题


I am trying to attach an handler to httpclientfactory using "ConfigurePrimaryHttpMessageHandler"

but when I look inside the HttpClient to see if the handler is there i cannot find it

Am I attaching the handler correctly?

Any Suggesions

     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);
        }
    }

回答1:


The code you have shown is the recommend approach.

The comment about _gitHubClient

//my _gitHubClient has no Handler attached!!!

seems like a misunderstanding.

_gitHubClient is your abstraction that is wrapping a HttpClient instance in its GitHubClient implementation.

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("/");
    }
}

It is that wrapped instance that would have the attached handler.

Based on the current configuration, whenever the framework has to create an instance of the IGitHubClient derived GitHubClient for injection, the factory will create a HttpClient using the settings provided at start up. Which would also include adding the HttpClientHandler provided by ConfigurePrimaryHttpMessageHandler



来源:https://stackoverflow.com/questions/51044441/attaching-httphandler-to-httpclientfactory-webapi-aspnetcore-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!