一、直接使用方式
不管是哪种方式,都要先注册服务,对于 ASP.NET Core 应用则是在 Startup.cs 文件的 ConfigureServices 添加如果代码:
services.AddHttpClient();
然后在 Controller 中通过构造注入的试获得 IHttpClientFactory,然后通过它来创建 HttpClient 对象。示例代码:
public class ValuesController : BaseController
{
private readonly IHttpClientFactory _httpClientFactory;
public ValuesController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async Task<ActionResult> Get()
{
var client = _httpClientFactory.CreateClient();
client.BaseAddress = new Uri("http://api.github.com");
string result = await client.GetStringAsync("/");
return Ok(result);
}
}
services.AddHttpClient();
services.AddHttpClient("github", c =>
{
c.BaseAddress = new Uri("https://api.github.com/");
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});
注意这里添加了两次 AddHttpClient,一次是没有命名的,一次是有命名的。在 Controller 中的使用方式是:
public class ValuesController : BaseController
{
private readonly IHttpClientFactory _httpClientFactory;
public ValuesController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async Task<ActionResult> Get()
{
var client = _httpClientFactory.CreateClient("github");
string result = await client.GetStringAsync("/");
return Ok(result);
}
}
public class GitHubClient
{
public HttpClient Client { get; private set; }
public GitHubClient(HttpClient httpClient)
{
httpClient.BaseAddress = new Uri("https://api.github.com/");
httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
Client = httpClient;
}
public async Task<string> GetData()
{
return await _client.GetStringAsync("/");
}
}
这里的 GetData 就是额外扩展的共用方法。使用前需要为这个类注册服务:
services.AddHttpClient<GitHubClient>();
然后在需要的地方(比如 Controller)中这样使用:
public class ValuesController : BaseController
{
private readonly GitHubClient _gitHubClient;;
public ValuesController(GitHubClient gitHubClient)
{
_gitHubClient = gitHubClient;
}
[HttpGet]
public async Task<ActionResult> Get()
{
string result = await _gitHubClient.GetData();
return Ok(result);
}
}
类型化的方式和命名式的方式相比,虽然在配置的时候会麻烦一点,但它有两个好处:
一是不用通过名称字符串来获得 Client,而是直接通过依赖注入获得具体的 Client;
二是可以在自定义的 HttpClient 类中扩展共用的方法。
转自:Liam Wang cnblogs.com/willick/p/net-core-httpclient.html
© 版权声明
博主的文章没有高度、深度和广度,只是凑字数。利用读书、参考、引用、抄袭、复制和粘贴等多种方式打造成自己的纯镀 24k 文章!如若有侵权,请联系博主删除。
喜欢就点个赞吧