在.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的使用的更多相关文章

  1. .NET Core 2.1中的HttpClientFactory最佳实践

    ASP.NET Core 2.1中出现一个新的HttpClientFactory功能, 它有助于解决开发人员在使用HttpClient实例从其应用程序发出外部Web请求时可能遇到的一些常见问题. 介绍 ...

  2. ASP.NET Core 2.1 中的 HttpClientFactory (Part 3) 使用Handler实现传出请求中间件

    原文:https://www.stevejgordon.co.uk/httpclientfactory-aspnetcore-outgoing-request-middleware-pipeline- ...

  3. ASP.NET Core 2.1 中的 HttpClientFactory (Part 4) 整合Polly实现瞬时故障处理

    原文:https://www.stevejgordon.co.uk/httpclientfactory-using-polly-for-transient-fault-handling发表于:2018 ...

  4. 在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务

    在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务 https://procodeguide.com/programming/polly-in-aspnet-core ...

  5. ASP.NET Core HTTP 管道中的那些事儿

    前言 马上2016年就要过去了,时间可是真快啊. 上次写完 Identity 系列之后,反响还不错,所以本来打算写一个 ASP.NET Core 中间件系列的,但是中间遇到了很多事情.首先是 NPOI ...

  6. 在.NET Core控制台程序中使用依赖注入

    之前都是在ASP.NET Core中使用依赖注入(Dependency Injection),昨天遇到一个场景需要在.NET Core控制台程序中使用依赖注入,由于对.NET Core中的依赖注入机制 ...

  7. ASP.NET Core 1.0 中的依赖项管理

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  8. 在ASP.NET Core 1.0中如何发送邮件

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...

  9. EF Core 1.0中使用Include的小技巧

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:由于EF Core暂时不支持Lazy Loading,所以利用Include来加载额外 ...

随机推荐

  1. call undefined function openssl_cipher_iv_length

    现象: 访问localhost/blog/public时,报错在verdor/framework/src/Illuminate/Encryption/Encrtpter.php的84行,找不到open ...

  2. 【js】 vue 2.5.1 源码学习(六) initProxy initLifeCycle 渲染函数的作用域代理

    大体思路 (五) 1. initProxy 渲染函数的作用域代理 ==> es6 如果支持proxy (hasProxy) 就用proxy 不支持就用 defineProperty() prox ...

  3. Moq基础 判断方法被执行

    如果想知道注入的类的某个方法被使用了几次,就可以通过 mock 提供的方法进行判断方法有没被执行或被使用多少次 本文是一个系列,具体请看 Moq基础(一) 为什么需要单元测试框架 Moq基础(二) 快 ...

  4. linux内核符号表

    我们已经看到 insmod 如何对应共用的内核符号来解决未定义的符号. 表中包含了全局内 核项的地址 -- 函数和变量 -- 需要来完成模块化的驱动. 当加载一个模块, 如何由模块 输出的符号成为内核 ...

  5. LightOJ - 1284 Lights inside 3D Grid (概率计算)

    题面: You are given a 3D grid, which has dimensions X, Y and Z. Each of the X x Y x Z cells contains a ...

  6. HDU - 4587 TWO NODES (图的割点)

    Suppose that G is an undirected graph, and the value of stab is defined as follows: Among the expres ...

  7. mac笔记本安装Android sdk

    一.先下载android sdk for mac   给二个靠谱的网址: a). http://down.tech.sina.com.cn/page/45703.html b). http://mac ...

  8. LabWindows/CVI基础

    1.LabWindows/CVI了解 提到NI公司,大家可能最先联想到的是NI公司推出的LabVIEW软件.LabWindows/CVI与LabVIEW相比,主要应用在各种测试.控制.故障分析及信息处 ...

  9. linux 更新jdk

    1.上传jdk版本的包 下载JDK地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.h ...

  10. 前端——jQuery介绍

    目录 jQuery介绍 jQuery的优势 jQuery内容: jQuery版本 jQuery对象 jQuery基础语法 查找标签 基本选择器 层级选择器: 基本筛选器: 属性选择器: 表单筛选器: ...