使用方式
IHttpClientFactory有四種模式:
* 基本用法
* 命名客戶端
* 類型化客戶端
* 生成的客戶端
基本用法
在?Startup.ConfigureServices?方法中,通過(guò)在?IServiceCollection?上調(diào)用?AddHttpClient?擴(kuò)展方法可以注冊(cè)?IHttpClientFactory
services.AddHttpClient();
注冊(cè)之后可以像依賴注入DI似得在類中通過(guò)構(gòu)造函數(shù)注入形式使用,偽代碼:
class A { private readonly IHttpClientFactory _clientFactory; public
A(IHttpClientFactory clientFactory) { _clientFactory= clientFactory; } Public
void Use() { var request=new HttpRequestMessage(HttpMethod.Get,"www.baidu.com")
;var client = _clientFactory.CreateClient(); var response = await
client.SendAsync(request);if (response.IsSuccessStatusCode) { Branches = await
response.Content.ReadAsAsync<IEnumerable<GitHubBranch>>(); } else {
GetBranchesError= true; Branches = Array.Empty<GitHubBranch>(); } } }
命名客戶端
也是在基本用法的基礎(chǔ)上增加配置參數(shù):例如增加一個(gè)baidu下的客戶端:
services.AddHttpClient("baidu",c=> { c.BaseAddress = new Uri("
https://api.baidu.com/"); //其他一些參數(shù) });
?
然后在使用的時(shí)候只是需要傳遞客戶端名稱就自動(dòng)使用baidu這個(gè)地址的基礎(chǔ)地址配置:
var client = _clientFactory.CreateClient("baidu");
類型化客戶端
說(shuō)的明白一點(diǎn)就是在使用類的構(gòu)造函數(shù)中可以直接接受HttpClient 類型,不用在使用IHttpClientFactory
接口的CreateClient方法創(chuàng)建,但是首要條件就是要先創(chuàng)建注入類型,然后在ConfigureServices?方法同時(shí)注入:
services.AddHttpClient<classHttp>();
注入類型:
public class classHttp { public HttpClient Client { get; } public
GitHubService(HttpClient client) { client.BaseAddress= new Uri("
https://api.baidu.com/"); //同ConfigureServices 中一樣設(shè)置一些其他參數(shù) Client = client; } }
生成的客戶端
這個(gè)我個(gè)人理解為就是配置使用第三方庫(kù),然后可以注入接口類型,接口中可以寫一些方法接口。然后通過(guò)接口類直接調(diào)用接口。
個(gè)人理解:就是類似于一個(gè)接口映射,地址映射似得。通過(guò)結(jié)合第三方庫(kù)(官方推薦Refit)實(shí)現(xiàn)請(qǐng)求一個(gè)地址別名的方式,別名就是指定義的接口。然后別名通過(guò)增加特性Get(“路徑”)或者post("路徑)的形式重新指向真實(shí)的請(qǐng)求接口地址。通過(guò)請(qǐng)求這個(gè)本地接口方法實(shí)現(xiàn)轉(zhuǎn)化請(qǐng)求的真實(shí)地址。
舉例定義接口:
public interface IHelloClient { [Get("/MyInterFace")] Task<Reply>
GetMessageAsync(); }
配置Refit插件:
也是和正常配置類似,在后面增加接口的服務(wù)注入。
public void ConfigureServices(IServiceCollection services) {
services.AddHttpClient("hello", c => { c.BaseAddress = new Uri("
http://localhost:5000"); }) .AddTypedClient(c =>
Refit.RestService.For<IHelloClient>(c)); services.AddMvc(); }
然后再說(shuō)接口上面的Get("/MyInterFace")方法;這個(gè)我們就不做另一個(gè)項(xiàng)目就在當(dāng)前項(xiàng)目下,所以可以直接就在api項(xiàng)目下創(chuàng)建一個(gè)名為MyInterFace的方法。
[ApiController] public class TestController : ControllerBase { [HttpGet("/")]
public async Task<sting> MyInterFace() { return "ceshi"; } }
然后就可以使用接口了:
[ApiController] public class ValuesController : ControllerBase { private
readonly IHelloClient _client; public ValuesController(IHelloClient client) {
_client= client; } [HttpGet("/")] public async Task<ActionResult<Reply>>
Index() {return await _client.GetMessageAsync(); } }
在這了的_client.GetMessageAsync()方法就是調(diào)用了接口方法,看著是調(diào)用了GetMessageAsync方法其實(shí)是做了映射,映射地址就是上面特性寫的MyInterFace方法。通過(guò)斷點(diǎn)也可以驗(yàn)證此結(jié)論。然后不同項(xiàng)目下也是同一個(gè)意思,假如我們請(qǐng)求百度的地址:www.baidu.com/api/b這個(gè)接口
我們?cè)谂渲贸霭颜?qǐng)求地址http://localhost:5000改為www.baidu.com/api,然后再把GetMessageAsync方法上面的MyInterFace改為b即可。
出站請(qǐng)求中間件
個(gè)人理解為請(qǐng)求返回前處理程序,就是繼承?DelegatingHandler派生類重寫SendAsync?方法。在將請(qǐng)求傳遞至管道中的下一個(gè)處理程序之前執(zhí)行代碼:
public class ValidateHeaderHandler : DelegatingHandler { protected override
async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request,
CancellationToken cancellationToken) {if (!request.Headers.Contains("X-API-KEY"
)) {return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new
StringContent("You must supply an API key header called X-API-KEY") }; } return
await base.SendAsync(request, cancellationToken); } }
然后在ConfigureServices中:
services.AddTransient<ValidateHeaderHandler>();//注冊(cè)處理程序 services.AddHttpClient(
"externalservice", c => { // Assume this is an "external" service which
requires an API KEY c.BaseAddress = new Uri("https://localhost:5000/"); })
.AddHttpMessageHandler<ValidateHeaderHandler>();/注入到http請(qǐng)求管道
?
可以同時(shí)注冊(cè)多個(gè)處理程序。
HttpClient和生存周期
每次對(duì)?IHttpClientFactory?調(diào)用?CreateClient?都會(huì)返回一個(gè)新?HttpClient?實(shí)例。?每個(gè)命名的客戶端都具有一個(gè)?HttpMessageHandler。?工廠管理?HttpMessageHandler?實(shí)例的生存期。
?HttpClient實(shí)例不是與HttpMessageHandler一起銷毀的,HttpMessageHandler在池中生存,如果生命周期未到不會(huì)被銷毀,會(huì)被新的HttpClient?實(shí)例使用。
處理程序的默認(rèn)生存周期是2分鐘,可以通過(guò)配置修改:
services.AddHttpClient("extendedhandlerlifetime")
.SetHandlerLifetime(TimeSpan.FromMinutes(5));
?原文有道云筆記連接:https://note.youdao.com/ynoteshare1/index.html?id=80912dd7064716428880a8e201b76a11&type=note
熱門工具 換一換
