我想为 Typed HttpClient 添加一个 HttClientHandler 以包含证书身份验证。
我在网上找到的所有例子都是这样的:
services.AddHttpClient<IMyService, MyService>()
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
// Set here whatever you need to get configured
};
});
Run Code Online (Sandbox Code Playgroud)
但是我不想在此处包含获取证书的所有逻辑,因此我想使用ConfigurePrimaryHttpMessageHandler<>的通用版本并编写自己的消息处理程序以在请求中包含证书。
问题是我很难理解我应该如何实现消息处理程序......我应该从HttpClientHandler继承吗?
请帮忙!
更新
正如我最初怀疑的那样,@Nkosi 证实,从 HttpClient 处理程序派生是这种情况下的方法。最后的代码类似于:
public class MyHttpClientHandler : HttpClientHandler
{
private readonly IMyConfiguration _myConfiguration;
public MyHttpClientHandler(IMyConfiguration myConfiguration)
{
_myConfiguration = myConfiguration;
using (var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
certStore.Open(OpenFlags.ReadOnly);
var certCollection = certStore.Certificates.Find(
X509FindType.FindBySerialNumber,
_myConfiguration.MyCertificateSerial,
true);
X509Certificate2 certificate = certCollection[0];
ClientCertificateOptions = ClientCertificateOption.Manual;
SslProtocols …
Run Code Online (Sandbox Code Playgroud) c# dotnet-httpclient .net-core httpclientfactory .net-core-2.1
我创建了一个简单的控制台应用程序,它使用新的 ASP.NET Core 2.1 HttpClientFactory从 archive.org 下载单个 (PDF) 文件。
对于该程序中使用的特定 URL,我总是得到一个TaskCanceledException
. 如果您尝试运行此代码,您可能会遇到相同的异常。不过,它适用于 archive.org 上的其他 URL。当使用 wget 从完全相同的 URL ( wget https://archive.org/download/1952-03_IF/1952-03_IF.pdf --output-document=IF.pdf
) 下载文件时,下载成功。
但是,当我这样做时,HttpClient
我得到以下异常。
我可能做错了什么?
这是简单的代码:
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using System.Diagnostics;
namespace test2
{
public class Program
{
public static async Task Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient("archive", c =>
{
c.BaseAddress = new Uri("https://archive.org/download/");
c.DefaultRequestHeaders.Add("Accept", "application/pdf");
})
.AddTypedClient<ArchiveClient>();
var services …
Run Code Online (Sandbox Code Playgroud) 我已经阅读了使用HttpClientFactory 的热门博客文章https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore
引用它
ASP.NET Core 2.1中将出现一个新的HttpClientFactory功能,它有助于解决开发人员在使用HttpClient实例从其应用程序发出外部Web请求时可能遇到的一些常见问题.
所有示例都显示在asp.net应用程序的启动类中连接它,例如
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHttpClient();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是你可以在ASP.NET核心之外使用吗?如果是这样的例子
我会想到很多非Web应用程序(.net核心应用程序)需要进行Web调用,那么为什么这不是.net core api的一部分而不是放入asp.net core api
我有一个 ASP.NET Core 2.1 项目,它使用基于 .Net Core 2.1 构建的类库。在 .Net Core 2.1 类库中,我需要创建几个 REST 类,为此我使用了 HttpClient 类。
我想利用 HttpClientFactory 的优势来创建和使用 HttpClient 实例。
如何在 .Net Core 2.1 类库中使用 HttpClientFactory。
将Blazor从0.5.1(使用Flurl)更新到0.6.0后,通过flurl调用会抛出异常:
WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method
because it was wiped. See stack trace for details.
Run Code Online (Sandbox Code Playgroud)
该项目创建了一个HttpClientFactory,它可以让Blazor的HttpClient被Flurl使用:
使用HttpClientFactoryForBlazor使用Blazor的HttpClient(http)创建FlurlClient:
IFlurlClient c = new FlurlClient() { Settings = new Flurl.Http.Configuration.ClientFlurlHttpSettings { HttpClientFactory = new HttpClientFactoryForBlazor(http) }};
Run Code Online (Sandbox Code Playgroud)
使用FlurlClient(c)例如通过Flurl的扩展方法"IFlurlRequest.WithClient(c);"
private class HttpClientFactoryForBlazor : Flurl.Http.Configuration.IHttpClientFactory
{
private readonly HttpClient httpClient;
public HttpClientFactoryForBlazor(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public virtual HttpClient CreateHttpClient(HttpMessageHandler handler)
{
return this.httpClient;
}
}
Run Code Online (Sandbox Code Playgroud)
所以,似乎这种方法不再起作用.
有谁知道如何使用Blazor 0.6.0制作Flurl?
Call-Stack是:
WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method because it was wiped. See …
Run Code Online (Sandbox Code Playgroud) 需要向需要特定cookie的服务器发出请求。能够使用 HTTP 客户端和带有 cookiecontainer 的处理程序来完成此操作。通过使用类型化客户端,无法找到设置 cookiecontainer 的方法。
使用http客户端:
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (HttpClient client = new HttpClient(handler))
{
//.....
// Used below method to add cookies
AddCookies(cookieContainer);
var response = client.GetAsync('/').Result;
}
Run Code Online (Sandbox Code Playgroud)
使用 HttpClientFactory:
在startup.cs中
services.AddHttpClient<TypedClient>().
ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
CookieContainer = new CookieContainer()
});
Run Code Online (Sandbox Code Playgroud)
在控制器类中
// Need to call AddCookie method here
var response =_typedclient.client.GetAsync('/').Result;
Run Code Online (Sandbox Code Playgroud)
在 Addcookie 方法中,我需要将 cookie 添加到容器中。任何建议如何做到这一点。
c# cookiecontainer dotnet-httpclient .net-core httpclientfactory
.NET Framework 版本:4.7.2 Autofac 版本:4.0.1.0
我想在我的 Global.asax 中注册 IHttpClientFactory 但我不能像在 .net core 中那样使用 services.AddHttpClient 。我需要 IHttpClientFactory 作为我自己的 http 客户端类的依赖项,我需要在我的 webapi 项目中引用它。
这甚至可能吗?如果是,它是如何完成的?
我有一个 .Net Core 项目需要连接到大约 4 个不同的 API 服务,我不是任何 HttpClient 代码的专家,但从我发现的情况来看,您通常只想重用一个实例你的 HttpClient。据我所知,普遍的共识是在 .Net Core 中使用 HttpClientFactory,方法是在您的 Startup 类中注册它,然后使用 DI 请求它。
现在,除了 BaseAddress url 之外,我的大多数默认标头等通常都相同,在连接到 4 个 diff API 服务时我应该如何处理?我应该注册 4 个不同的命名客户端,还是让一个客户端预先设置所有默认信息,然后根据需要手动配置它,例如配置地址?
一般问题是因为我对此还很陌生,据说它会重用 HttpClient 的一个实例。
任何帮助澄清将不胜感激,
谢谢!
我想使用Polly应用弹性策略。我正在使用 ASP.NET Core 2.1 中的 HttpClientFactory。我在Polly GitHub wiki上找到了一些指南。这种策略配置有两种方式——使用 AddTransientHttpErrorPolicy 和 AddPolicyHandler,但不多解释。它们之间有什么区别?
resiliency microservices polly asp.net-core-webapi httpclientfactory
我在服务层有一个方法来连接到服务,并且我正在使用IHttpClientFactory
. 我的方法运行良好。现在我正在尝试为此编写单元测试用例。
public async Task<MyObject> MyMethodAsync(string arg1, string arg2)
{
var client = _httpClientFactory.CreateClient("XYZ");
var Authkey = "abc";
var AuthToken = "def";
var headers = new Dictionary<string, string>
{
{ Authkey,AuthToken }
};
client.AddTokenToHeader(headers); //This method set the DefaultRequestheader from the dictionary object
var reqData = new
{
prop1 = "X",
prop2 = "Y"
};//req object
var content = new StringContent(JsonConvert.SerializeObject(reqData), Encoding.UTF8, "application/json");
//This is httpClient Post call for posting data
HttpResponseMessage response = await client.PostAsync("postData", content);
if …
Run Code Online (Sandbox Code Playgroud) c# unit-testing dotnet-httpclient asp.net-core httpclientfactory
c# ×5
asp.net-core ×4
.net-core ×3
.net ×1
autofac ×1
blazor ×1
flurl ×1
polly ×1
resiliency ×1
unit-testing ×1