前言
以前写过的文章 Asp.net core 学习笔记 ( HttpClient ).
其实 HttpClient 内容是挺多的, 但是我自己用到的很少. 所以这篇记入一下自己用到的就好了.
参考
3 ways to use HTTPClientFactory in ASP.NET Core 2.1
Docs – Make HTTP requests using IHttpClientFactory in ASP.NET Core
3 大用法介绍
其实是 4 种哦, 只是第 4 种我不熟就忽略掉呗.
Basic usage 的方式是注入 HttpClientFactory > 创建 HttpClient > 发 request
Named clients 的方式是先在 program.cs provide 好 config, 比如 Uri, default header 等等. 然后注入 HttpClientFactory > 创建 HttpClient with named config > 发 request.
如果你要发多个不同的 path 但是相同的 origin 的话, 这个管理方式会比 Basic usage 好.
Typed clients 的方式是先做一个 service class, 在 constructor 注入 HttpClient 然后配置 config, 提供各做方法里面使用 HttpClient 发 request.
这个方式主要就是封装了所以对这个 client 的请求, 外部只要 call service 的 method 就好.
对比 3 大用法
可以看出来, 主要就是在管理上的区别. 个人建议, 如果只是 1 个请求, 那么直接用 basic 就好了, 如果多个请求, 或者多个地方用到, 那么就用 Type clients. 至于 Named clients 感觉有点不上不下就不要用了.
Get Request (Basic usage)
要到这里 Github – CountryCodes.json 请求 Country Code JSON
Provide HttpClient
builder.Services.AddHttpClient();
注入 HttpClientFactory
private readonly IHttpClientFactory _httpClientFactory; public IndexModel( IHttpClientFactory httpClientFactory ) { _httpClientFactory = httpClientFactory; }
创建 Request Message
var httpRequestMessage = new HttpRequestMessage { RequestUri = new Uri("https://gist.githubusercontent.com/Goles/3196253/raw/9ca4e7e62ea5ad935bb3580dc0a07d9df033b451/CountryCodes.json"), Method = HttpMethod.Get, }; httpRequestMessage.Headers.Add("Accept", "application/json; charset=utf-8");
调用 HttpClient 发请求
var httpClient = _httpClientFactory.CreateClient(); var response = await httpClient.SendAsync(httpRequestMessage); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); }
以上就是 basic usage 的方式. 类似发 SMTP 请求那样.
解析 JSON response
另外, 也可以直接解析 JSON response
public class Country { public string Name { get; set; } = ""; [JsonPropertyName("dial_code")] public string DialCode { get; set; } = ""; public string Code { get; set; } = ""; } var counties = await response.Content.ReadFromJsonAsync<List<Country>>();
Get Request (Typed clients)
创建 Client
public class CountryCodeHttpClient { private readonly HttpClient _httpClient; public CountryCodeHttpClient( HttpClient httpClient ) { _httpClient = httpClient; _httpClient.BaseAddress = new Uri("https://gist.githubusercontent.com"); _httpClient.DefaultRequestHeaders.Add("Accept", "application/json; charset=utf-8"); } public async Task<List<Country>> GetCountriesAsync() { var response = await _httpClient.GetAsync("/Goles/3196253/raw/9ca4e7e62ea5ad935bb3580dc0a07d9df033b451/CountryCodes.json"); if (response.IsSuccessStatusCode) { return (await response.Content.ReadFromJsonAsync<List<Country>>())!; } else { throw new Exception("error"); } } }
通常 Client 在 construtor 会配置通用的 URI 和 Header. 在方法内则控制 path 和 extra Header.
Provide HttpClient
builder.Services.AddHttpClient<CountryCodeHttpClient>();
调用
var counties = await _countryCodeHttpClient.GetCountriesAsync();
TODO post request 等等...