每个请求更改安全协议(HttpClient)

编程入门 行业动态 更新时间:2024-10-22 19:37:22
本文介绍了每个请求更改安全协议(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)

本文发布于:2023-11-08 13:46:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569540.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:协议   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!