对HttpClient
的建议是对reuse a single instance。但是从API看来,添加证书的方法似乎是在实例上,而不是每个请求上。如果添加两个证书,例如,如何确保仅将“证书1”发送到“ one.somedomain.com”?
//A handler is how you add client certs (is there any other way?)
var _clientHandler = new HttpClientHandler();
//Add multiple certs
_clientHandler.ClientCertificates.Add(cert1);
_clientHandler.ClientCertificates.Add(cert2);
_clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
//Pretend this is our long-living HttpClient
var client = new HttpClient(_clientHandler);
//Now if we make a post request, will both certs be used?
using (HttpResponseMessage response = _client.PostAsync("https://one.somedomain.com", content).Result)
{
//...elided...
}
参考方案
抱歉。年末很多工作。
哟可以尝试实现这样的东西:
public class CustomHttpHandler : HttpClientHandler
{
private readonly Dictionary<string, X509Certificate> _certMap;
public CustomHttpHandler():base()
{
_certMap = new Dictionary<string, X509Certificate>() { { "server1name", new X509Certificate("cert1") }, { "server2name", new X509Certificate("cert2") } };
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
string serverName = request.RequestUri.Host;
if (ClientCertificates.Contains(_certMap[serverName]))
{
try
{
var response = await base.SendAsync(request, cancellationToken);
return response;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
throw;
}
}
else
{
ClientCertificates.Clear();
ClientCertificates.Add(_certMap[serverName]);
try
{
var response = await base.SendAsync(request, cancellationToken);
return response;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
throw;
}
}
}
}
只是一个想法,未经测试。
或者,您也可以在Headers
实例中使用RequestMessage
集合。
本文介绍了以下主题:https://damienbod.com/2019/09/07/using-certificate-authentication-with-ihttpclientfactory-and-httpclient/
在ASP.NET Core依赖注入中,我只是想知道注册Singleton实例是否会比注册Transient实例更好地提高性能?在我看来,对于Singleton实例,创建新对象和相关对象只需花费一次时间。对于Transient实例,此成本将针对每个服务请求重复。因此Singleton似乎更好。但是,在Singleton上使用Transient时,我们可以获得多…
如何在ASP.NET Core Web应用程序中增加JSON反序列化MaxDepth限制 - c#我们正在将ASP.NET Core 2.1与.NET Framework 4.6.2结合使用。我们有一个客户需要向我们的Web应用程序发送一个很大程度上嵌套的json结构。当他们进行此调用时,我们将输出以下日志并返回错误: 读取器的MaxDepth超过了32。路径“ super.long.path.to property”,第1行,位置42111。”我浏览了…
ASP.NET Core-在Singleton注入上存储库依赖项注入失败 - c#我正在使用SoapCore为我的ASP.NET Core MVC应用程序创建Web服务。我正在使用Entity Framework Core和简单的存储库模式来获取我的数据库数据。我通过Startup.cs中的.AddSingleton()注入存储库类:services.AddSingleton<IImportRepository, ImportRep…
从Axios请求以ASP.NET Core API返回下载文件 - c#大家好我正在尝试从Axios Request从ASP.NET Core Web API下载文件。这是我的示例API方法。 (基于此stackoverflow question的代码)[HttpPost("download")] public async Task<IActionResult> DownloadFile(){ .…
从.NET Core 2.1降级到.NET 4.7.1时,如何使用IApplicationBuilder和IServiceCollection? - c#我不得不将我的项目从.NET Core 2.1更改为.NET 4.7.1,并且修复了几乎所有错误,但以下错误仍然困扰着我 “ IApplicationBuilder”不包含“ UseHsts”的定义,也找不到找不到接受类型为“ IApplicationBuilder”的第一个参数的扩展方法“ UseHsts”(是否缺少using指令或程序集引用?) “ IA…