在 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