Do HttpClient and HttpClientHandler have to be disposed between requests?

前端 未结 12 2193
鱼传尺愫
鱼传尺愫 2020-11-22 02:06

System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker).

The usin

12条回答
  •  暖寄归人
    2020-11-22 02:31

    Since it doesn't appear that anyone has mentioned it here yet, the new best way to manage HttpClient and HttpClientHandler in .NET Core 2.1 is using HttpClientFactory.

    It solves most of the aforementioned issues and gotchas in a clean and easy-to-use way. From Steve Gordon's great blog post:

    Add the following packages to your .Net Core (2.1.1 or later) project:

    Microsoft.AspNetCore.All
    Microsoft.Extensions.Http
    

    Add this to Startup.cs:

    services.AddHttpClient();
    

    Inject and use:

    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
    
        public ValuesController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }
    
        [HttpGet]
        public async Task Get()
        {
            var client = _httpClientFactory.CreateClient();
            var result = await client.GetStringAsync("http://www.google.com");
            return Ok(result);
        }
    }
    

    Explore the series of posts in Steve's blog for lots more features.

提交回复
热议问题