每个请求更改安全协议(HttpClient) [英] Changing security protocol per request (HttpClient)

查看:133
本文介绍了每个请求更改安全协议(HttpClient)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个必须与几种不同服务进行通信的Web API。目前,我将Web API设置为使用以下安全协议:

I've got a Web API that must communicate with a few different services. Currently, I have the Web API set to use the following security protocol:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

当API通过 HttpClient (比如Twitter)调用另一个服务时,它将使用该协议。然而,与此同时,另一个请求可能会从云中访问某些内容,无论出于何种原因,目前需要TLS(而不是TLS 1.2)。在发出之前,对云的请求再次设置安全协议:

When the API calls out to another service via HttpClient (say like Twitter), it will use that protocol. 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). The request to the cloud, before firing out, sets the security protocol again:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

我遇到的问题是当两个独立且独特的请求进入时,一个用于Twitter,一个用于云,安全协议可以切换到发出之前的错误的,导致请求失败。

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.

有没有办法在每个请求的 HttpClient 上设置安全协议,这样我就可以了不是在某个单独的某个单位周围交换?

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?

推荐答案

你不需要设置 it。

您可以使用:

using System.Net;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

附加说明:


  • .Net 4.5需要因为Tls12不是默认协议。

  • 只需在应用程序中编写一次上述代码。 (例如,在Web应用程序中的Global.asax> Application_Start或Winforms应用程序中的等效内容)

  • 对于.Net 4.6及更高版本,Tls12是默认协议,因此不需要

这篇关于每个请求更改安全协议(HttpClient)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆