.NET6之MiniAPI(二十二):HttpClient
阿新 • • 發佈:2022-11-29
說明:本篇不是說明HttpClient怎麼使用,而以分享在asp.net core mini api框架下,HttpClient的引入和使用方式。
我們在業務開發中,免不了呼叫三方的服務,這時就會用到HttpClient,在早期的asp.net core框架中,一般是通過new HttpClient來實現對三方的請求,現在,可以通過HttPClientFactory來實現,這樣的好處是可以池化連線,節省資源。
基礎使用方法很簡單:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
var app = builder.Build();
app.MapGet("/test", async (IHttpClientFactory clientFactory) =>
{
var client = clientFactory.CreateClient();
var content = await client.GetStringAsync("https://www.google.com");
});
app.Run();
當專案中有多個三方服務請求,為了區分各個三方服務,可以採用命名方式
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient( "Google", httpClient =>
{
httpClient.BaseAddress = new Uri("https://www.google.com/");
});
builder.Services.AddHttpClient("BaiDu", httpClient =>
{
httpClient.BaseAddress = new Uri("https://www.baidu.com/");
});
var app = builder.Build();
app.MapGet("/testgoogle", async (IHttpClientFactory clientFactory) =>
{
var googleClient = clientFactory.CreateClient("Google");
return await googleCclient.GetStringAsync("search?q=桂素偉");
});
app.MapGet("/testbaidu", async (IHttpClientFactory clientFactory) =>
{
var baiduClient = clientFactory.CreateClient("BaiDu");
return await lient .GetStringAsync("s?wd=桂素偉");
});
app.Run();
還可以專案中每個服務的請求各自封裝,各用各的HttpClient:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<IGoogleService, GoogleService>();
builder.Services.AddHttpClient<IBaiDuService, BaiDuService>(httpClient =>
{
httpClient.BaseAddress = new Uri("https://www.baidu.com/");
});
var app = builder.Build();
app.MapGet("/testgoogle", async (IGoogleService google) =>
{
return await google.GetContentAsync();
});
app.MapGet("/testbaidu", async (IBaiDuService baidu) =>
{
return await baidu.GetContentAsync();
});
app.Run();
interface IGoogleService
{
Task<string> GetContentAsync();
}
class GoogleService : IGoogleService
{
private readonly HttpClient _httpClient;
public GoogleService(HttpClient httpClient)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri("https://www.google.com/");
}
public async Task<string> GetContentAsync()
{
return await _httpClient.GetStringAsync("search?q=桂素偉");
}
}
interface IBaiDuService
{
Task<string> GetContentAsync();
}
class BaiDuService : IBaiDuService
{
private readonly HttpClient _httpClient;
public BaiDuService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetContentAsync()
{
return await _httpClient.GetStringAsync("s?wd=桂素偉");
}
}
想要更快更方便的瞭解相關知識,可以關注微信公眾號