.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来加载额外 ...
随机推荐
- SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法
楼主今天在学习SpringBoot集成thymelaf的时候报了中文乱码的错误,经过网上的搜索,现在得到解决的办法,分享给大家: package com.imooc.config; import or ...
- H3C 其他OSPF显示命令
- 【React】 npm 常用的插件
npm install –save-dev package.json 安装环境 https://segmentfault.com/a/1190000008489881 全局 https:/ ...
- 给培训学校讲解ORM框架的课件
导读:这是我给某培训学校培训.net程序员所设计的课件,他们普遍反映太难了,是这样吗?
- AutoHotKey 用打码的快捷键
本文告诉大家如何使用 AutoHotKey 将 - 键默认输入的时候是下划线,因为使用下划线在写代码的时候是用在私有字段,而 - 很少使用 我打码经常需要使用下划线_而下划线需要按shift+- 两个 ...
- Linux 内核SBus连接
当大部分计算机配备有 PCI 或 ISA 接口总线, 大部分老式的基于 SPARC 的工作站使用 SBus 来连接它们的外设. SBus 使一个非常先进的设计, 尽管它已出现很长时间. 它意图是处理器 ...
- python数据分析经常使用的库
这个列表包含数据分析经常使用的Python库,供大家使用.1. 网络通用urllib -网络库(stdlib).requests -网络库.grab – 网络库(基于pycurl).pycurl – ...
- JAVA兼职架构师
在一些小企业或者公司人力不足的时候,经常会出现一个人干多个人的活.开发可能会干架构.测试.运维,一些小项目可能需要一个人完成.我把这些角色合并在一起称之为兼职架构师. 我用我的经历来说说兼职架构师的需 ...
- 谈谈模型融合之一 —— 集成学习与 AdaBoost
前言 前面的文章中介绍了决策树以及其它一些算法,但是,会发现,有时候使用使用这些算法并不能达到特别好的效果.于是乎就有了集成学习(Ensemble Learning),通过构建多个学习器一起结合来完成 ...
- 利用docker容器运行.net core webapi
利用docker容器运行.net core webapi :first-child { margin-top: 0 !important; } > :last-child { margin-bo ...