在 Asp.Net Core 1.0 时代,因为设计上的问题, HttpClient 给开发者带来了无尽的困扰,用 Asp.Net Core 开发团队的话来讲就是:咱们注意到,HttpClient 被不少开发人员不正确的使用。得益于 .Net Core 不断的版本快速升级;解决方案也一一浮出水面,本文尝试从各个业务场景去剖析 HttpClient 的各类使用方式,从而在开发中正确的使用 HttpClient 进行网络请求。html
public HttpClient CreateHttpClient() { return new HttpClient(); } // 或者 public async Task<string> GetData() { using (var client = new HttpClient()) { var data = await client.GetAsync("https://www.cnblogs.com"); } return null; }
private static HttpClient httpClient = null; public HttpClient CreateHttpClient() { if (httpClient == null) httpClient = new HttpClient(); return httpClient; }
An error occurred while sending the request. Couldn't resolve host name An error occurred while sending the request. Couldn't resolve host name
public void ConfigureServices(IServiceCollection services) { ... services.AddHttpClient(); }
public class ValuesController : ControllerBase { private HttpClient httpClient; public ValuesController(HttpClient httpClient) { this.httpClient = httpClient; } ... }
public HttpClient CreateHttpClient() { return HttpClientFactory.Create(); }
public class WeatherService { private HttpClient httpClient; public WeatherService(HttpClient httpClient) { this.httpClient = httpClient; this.httpClient.BaseAddress = new Uri("http://www.weather.com.cn"); this.httpClient.Timeout = TimeSpan.FromSeconds(30); } public async Task<string> GetData() { var data = await this.httpClient.GetAsync("/data/sk/101010100.html"); var result = await data.Content.ReadAsStringAsync(); return result; } }
public void ConfigureServices(IServiceCollection services) { ... services.AddHttpClient(); } // 而后,在控制器中使用以下代码 [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private WeatherService weatherService; public ValuesController(WeatherService weatherService) { this.weatherService = weatherService; } [HttpGet] public async Task<ActionResult> Get() { string result = string.Empty; try { result = await weatherService.GetData(); } catch { } return new JsonResult(new { result }); } }
{ result: "{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"27.9","WD":"南风","WS":"小于3级","SD":"28%","AP":"1002hPa","njd":"暂无实况","WSE":"<3","time":"17:55","sm":"2.1","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB"}}" }
首先须要从 NuGet 中引用包
Polly
Polly.Extensions.Httplinux
public void ConfigureServices(IServiceCollection services) { ... services.AddHttpClient<WeatherService>() .SetHandlerLifetime(TimeSpan.FromMinutes(5)) .AddPolicyHandler(policy => { return HttpPolicyExtensions.HandleTransientHttpError() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(2), (exception, timeSpan, retryCount, context) => { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("请求出错了:{0} | {1} ", timeSpan, retryCount); Console.ForegroundColor = ConsoleColor.Gray; }); }); }
https://github.com/lianggx/EasyAspNetCoreDemo/tree/master/Ron.HttpClientDemogit