当前位置 : 主页 > 网络编程 > net编程 >

.NET6之MiniAPI(二十二):HttpClient

来源:互联网 收集:自由互联 发布时间:2023-09-03
说明:本篇不是说明HttpClient怎么使用,而以分享在asp.net core mini api框架下,HttpClient的引入和使用方式。 我们在业务开发中,免不了调用三方的服务,这时就会用到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之MiniAPI(二十二):HttpClient_asp.net

 

上一篇:.NET6之MiniAPI(二十三):Refit
下一篇:没有了
网友评论