.NET6之Mini API【二十二、HttpClient】

说明:本篇不是说明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之MiniAPIPDF版本下载地址 https://club.51aspx.com/circle/10569.html

给TA打赏
共{{data.count}}人
人已打赏
.NET

.NET6之Mini API【二十一、限流】

2022-7-8 20:54:12

.NET

.NET6之Mini API【二十三、Refit】

2022-7-12 20:43:57

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
今日签到
有新私信 私信列表
搜索