哪里有手机网站建设公司,网站建设促销活动,购物网站建设思路,乐东黎族自治县住房建设局网站说明#xff1a;本篇不是说明HttpClient怎么使用#xff0c;而以分享在asp.net core mini api框架下#xff0c;HttpClient的引入和使用方式。我们在业务开发中#xff0c;免不了调用三方的服务#xff0c;这时就会用到HttpClient#xff0c;在早期的asp.net core框架中本篇不是说明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.AddHttpClientIGoogleService, GoogleService();
builder.Services.AddHttpClientIBaiDuService, 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
{Taskstring GetContentAsync();
}
class GoogleService : IGoogleService
{private readonly HttpClient _httpClient;public GoogleService(HttpClient httpClient){_httpClient httpClient;_httpClient.BaseAddress new Uri(https://www.google.com/);}public async Taskstring GetContentAsync(){return await _httpClient.GetStringAsync(search?q桂素伟);}
}
interface IBaiDuService
{Taskstring GetContentAsync();
}
class BaiDuService : IBaiDuService
{private readonly HttpClient _httpClient;public BaiDuService(HttpClient httpClient){_httpClient httpClient;}public async Taskstring GetContentAsync(){return await _httpClient.GetStringAsync(s?wd桂素伟);}
}