[英]Changing security protocol per request (HttpClient)
I've got a Web API that must communicate with a few different services. 我有一个Web API,必须与几个不同的服务进行通信。 Currently, I have the Web API set to use the following security protocol:
目前,我将Web API设置为使用以下安全协议:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
When the API calls out to another service via HttpClient
(say like Twitter), it will use that protocol. 当API通过
HttpClient
(比如Twitter)调用另一个服务时,它将使用该协议。 At the same time however, another request may come in to access something from the cloud, which for whatever reason, currently requires TLS (not TLS 1.2). 然而,与此同时,另一个请求可能会从云访问某些内容,无论出于何种原因,目前需要TLS(而不是TLS 1.2)。 The request to the cloud, before firing out, sets the security protocol again:
在发出之前,对云的请求再次设置安全协议:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
The problem I'm running into is when two separate and unique requests come in, one for Twitter and one for the cloud, the security protocol could switch over to the "wrong one" before it's sent out, causing the request to fail. 我遇到的问题是当两个独立且唯一的请求进入时,一个用于Twitter,一个用于云,安全协议可能在发送之前切换到“错误的一个”,导致请求失败。
Is there a way to set the security protocol on the HttpClient
per request so that I'm not swapping around a setting in some singleton somewhere? 有没有办法在每个请求的
HttpClient
上设置安全协议,这样我就不会在某个单独的某个地方交换设置?
You don't need to set it. 您无需进行设置 。
You can use: 您可以使用:
using System.Net;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
Additional Notes: 补充笔记:
There seems to be no way to do this. 似乎没有办法做到这一点。 The
SecurityProtocol
property is only being used inside the internal TlsStream
class in one place: SecurityProtocol
属性仅在一个位置内部TlsStream
类中使用:
TlsStream
seems to back all the internal TLS connections such as HTTP, FTP and SMTP. TlsStream
似乎支持所有内部TLS连接,如HTTP,FTP和SMTP。
I had hoped that ServicePoint
allows you to configure this. 我曾希望
ServicePoint
允许您配置它。 For many settings ServicePointManager
only provides the default. 对于许多设置,
ServicePointManager
仅提供默认设置。 That hope was unfounded. 这种希望是没有根据的。
So this is quite strong evidence that this is not possible. 所以这是非常有力的证据,证明这是不可能的。 It's no proof, though.
但这并不能证明这一点。
What should you do? 你该怎么办? I'd switch out the HTTP client library for the odd server you are talking to.
我将为您正在与之交谈的奇数服务器切换HTTP客户端库。 HTTP is not a particularly complicated protocol.
HTTP不是一个特别复杂的协议。 I'm sure there's some other implementation available.
我确信还有其他一些实现可用。
Alternatively, use a proxy that terminates the HTTPS connection on your own server. 或者,使用在您自己的服务器上终止HTTPS连接的代理。 .NET then only deals with HTTP.
.NET然后只处理HTTP。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.