.net core 2.2 中IHttpClientFactory的使用
在.net core中使用HttpClient请求api,有很多资源的问题,比如使用using的时候,虽然可以释放资源,但是套接字(socket)也不会立即释放,所以.net core2.1中,新增了IHttpClientFactory.将其用于配置和创建应用中的 HttpClient 实例。 这能带来以下好处:
- 提供一个中心位置,用于命名和配置逻辑
HttpClient实例。 例如,可注册和配置 github 客户端,使其访问 GitHub。 可以注册一个默认客户端用于其他用途。 - 通过委托
HttpClient中的处理程序整理出站中间件的概念,并提供适用于基于 Polly 的中间件的扩展来利用概念。 - 管理基础
HttpClientMessageHandler实例的池和生存期,避免在手动管理HttpClient生存期时出现常见的 DNS 问题。 - (通过
ILogger)添加可配置的记录体验,以处理工厂创建的客户端发送的所有请求。
一、基本用法
在 Startup中的ConfigureServices中
services.AddHttpClient();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Content; namespace WebApplication1.Controllers
{
public class TestController : Controller
{
private readonly IHttpClientFactory _clientFactory;public TestController(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
} /// <summary>
/// 基本用法
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<string> Get()
{
HttpClient client = _clientFactory.CreateClient(); //方法一:
HttpRequestMessage request = new HttpRequestMessage
{
Method = new HttpMethod("get"),
RequestUri = new System.Uri("http://127.0.0.1:8067/api/values"),
};
HttpResponseMessage response = await client.SendAsync(request);
string res = await response.Content.ReadAsStringAsync();
return res; ////方法二:
//string res = await client.GetStringAsync("http://127.0.0.1:8067/api/values/1");
//return res;
}public IActionResult Index()
{
var aa= Get();
var bb = aa.Result;return View();
} }
}
二、命名客户端
在 Startup中的ConfigureServices中
//命名客户端
services.AddHttpClient("test", c =>
{
c.BaseAddress = new Uri("http://127.0.0.1:8067");
});
/// <summary>
/// 命名客户端
/// </summary>
/// <returns></returns>
public async Task<string> Get()
{
HttpClient client = _clientFactory.CreateClient("test");
//注册名叫 "test" 的客户端时,已经指定了该客户端的请求基地址,所以这里不需要指定主机名了
return await client.GetStringAsync("api/values");
}
三、类型化客户端
在 Startup中的ConfigureServices中 ,这里就是注入时配置HttpClient
//类型化客户端
services.AddHttpClient<TestHttpClient>(c =>
{
//可以在这里设置,也可以在构造函数设置.
//c.BaseAddress = new System.Uri("http://127.0.0.1:8067");
});
新建个类 TestHttpClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks; namespace WebApplication1.Content
{
public class TestHttpClient
{
public HttpClient Client { get; set; } public TestHttpClient(HttpClient client)
{
client.BaseAddress = new System.Uri("http://127.0.0.1:8067");
Client = client;
} public async Task<string> Get(string url)
{
return await Client.GetStringAsync(url);
} public async Task<HttpResponseMessage> Post<T>(string url,T t)
{
return await Client.PostAsJsonAsync(url,t);
}
}
}
/// <summary>
/// 类型化客户端
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<string> Get()
{
return await _client.Get("api/values");
} public async Task<HttpResponseMessage> Post()
{
//若返回400 则原因可能是本地客户端参数与api参数不一致
Text t = new Text() { value = "" };
return await _client.Post("api/values", t);
} public IActionResult Index()
{
var aa= Get();
var bb = aa.Result;
var cc = Post();
var dd = cc.Result;
if (dd.IsSuccessStatusCode)
{
var res = dd.Content.ReadAsStringAsync();
var ee= res.Result;
}
return View();
} public class Text
{
public string value { get; set; }
}
api这边就是默认的,改了个post 参数类型要一致
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; namespace Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
} // GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
} // POST api/values
[HttpPost]
public string Post([FromBody]Text value)
{
return "post method";
} // PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
} // DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
public class Text
{
public string value { get; set; }
}
}
可以将 HttpClient 完全封装在类型化客户端中。 不是将它公开为属性,而是可以提供公共方法,用于在内部调用 HttpClient。
参考资料:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2
.net core 2.2 中IHttpClientFactory的使用的更多相关文章
- .NET Core 2.1中的HttpClientFactory最佳实践
ASP.NET Core 2.1中出现一个新的HttpClientFactory功能, 它有助于解决开发人员在使用HttpClient实例从其应用程序发出外部Web请求时可能遇到的一些常见问题. 介绍 ...
- ASP.NET Core 2.1 中的 HttpClientFactory (Part 3) 使用Handler实现传出请求中间件
原文:https://www.stevejgordon.co.uk/httpclientfactory-aspnetcore-outgoing-request-middleware-pipeline- ...
- ASP.NET Core 2.1 中的 HttpClientFactory (Part 4) 整合Polly实现瞬时故障处理
原文:https://www.stevejgordon.co.uk/httpclientfactory-using-polly-for-transient-fault-handling发表于:2018 ...
- 在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务
在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务 https://procodeguide.com/programming/polly-in-aspnet-core ...
- ASP.NET Core HTTP 管道中的那些事儿
前言 马上2016年就要过去了,时间可是真快啊. 上次写完 Identity 系列之后,反响还不错,所以本来打算写一个 ASP.NET Core 中间件系列的,但是中间遇到了很多事情.首先是 NPOI ...
- 在.NET Core控制台程序中使用依赖注入
之前都是在ASP.NET Core中使用依赖注入(Dependency Injection),昨天遇到一个场景需要在.NET Core控制台程序中使用依赖注入,由于对.NET Core中的依赖注入机制 ...
- ASP.NET Core 1.0 中的依赖项管理
var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...
- 在ASP.NET Core 1.0中如何发送邮件
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...
- EF Core 1.0中使用Include的小技巧
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:由于EF Core暂时不支持Lazy Loading,所以利用Include来加载额外 ...
随机推荐
- H5 数据存储localStorage
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 12627 - Erratic Expansion——[递归]
Piotr found a magical box in heaven. Its magic power is that if you place any red balloon inside it ...
- H3C FTP配置示例
- java 类加载器的委托机制
l 当Java虚拟机要加载一个类时,到底派出哪个类加载器去加载呢? 1.首先当前线程的类加载器去加载线程中的第一个类. 2.如果类A中引用了类B,Java虚拟机将使用加载类A的类装载器来加载类B. 3 ...
- mysql 添加索引,ALTER TABLE和CREATE INDEX的区别
nvicat-->mysql表设计-->创建索引. (1)使用ALTER TABLE语句创建索引,其中包括普通索引.UNIQUE索引和PRIMARY KEY索引3种创建索引的格式: PRI ...
- 新手该如何学习JavaScript ?
JavaScript入门 - 01 准备工作 在正式的学习JavaScript之前,我们先来学习一些小工具,帮助我们更好的学习和理解后面的内容. js代码位置 首先是如何编写JavaScript代码, ...
- tf.squeeze()
转载自:https://www.cnblogs.com/mdumpling/p/8053376.html 原型 tf.squeeze(input, squeeze_dims=None, name=No ...
- 递归&时间模块&os模块
递归 递归调用 一个函数,调用了自身,称为递归调用 递归函数:一个会调用自身的函数称为递归函数 凡是循环能干的事,递归都能干 方式: 写出临界条件 找这一次和上一次的关系 假设当前函数已经能用,调用自 ...
- CSS3侧栏滑出简单实现
使用css3 的 animation 属性实现的点击滑出侧栏 <!DOCTYPE html> <html lang="en"> <head> & ...
- hdu 6851 Vacation(思维+贪心)
传送门 •题意 有编号0到n,n+1辆车排队过红绿灯,从0到n离交通灯线越来越近 每辆车都有一个最大速度v,车身长度l,和离交通灯线的距离s, 一辆车头到达线则说明这辆车已到达线 如果一辆车前面没有紧 ...