概述
说明:本篇不是说明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=桂素伟");
}
}
最后
以上就是刻苦鸵鸟为你收集整理的.NET6之MiniAPI(二十二):HttpClient的全部内容,希望文章能够帮你解决.NET6之MiniAPI(二十二):HttpClient所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复