gpt4 book ai didi

c# - 如何在 .net core 2.1 中忽略 SSL 验证

转载 作者:太空宇宙 更新时间:2023-11-03 13:49:41 24 4
gpt4 key购买 nike

我正在尝试调用部署在 Linux 服务器上的 Web 服务,该服务器具有来自在 .net 核心中开发并部署在 IIS 服务器(Windows 服务器 2012)上的应用程序的自签名证书。

但是当我尝试调用端点时,会抛出下一个错误:

"Message": "The SSL connection could not be established, see inner exception.", "Description": "InnerError : System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> System.ComponentModel.Win32Exception: Mensaje recibido inesperado, o bien su formato es incorrecto\r\n --- End of inner exception stack trace ---\r\n at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)\r\n at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.PartialFrameCallback(AsyncProtocolRequest asyncRequest)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Net.Security.SslState.ThrowIfExceptional()\r\n at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)\r\n at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result)\r\n at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)\r\n at System.Net.Security.SslStream.<>c.b__47_1(IAsyncResult iar)\r\n at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult
iar, Func
2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) | stackTrace : at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)\r\n at System.Threading.Tasks.ValueTask1.get_Result()\r\n at
System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage
request, CancellationToken cancellationToken)\r\n at
System.Threading.Tasks.ValueTask
1.get_Result()\r\n at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1
creationTask)\r\n at
System.Threading.Tasks.ValueTask
1.get_Result()\r\n at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)\r\n at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)\r\n at ReservasProxy.Data.APIConnection.CallXMLFormDataApiPostAsyc(String body) in C:\gitProjects\ResevasProxy\ReservasProxy\ReservasProxy\Data\APIConnection.cs:line 181\r\n

我已经尝试了下一个解决方案,但它们没有用。

解决方案 1:

          using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
// Make your request...
//send request
using (var httpClient = new HttpClient(httpClientHandler))
{

var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
HttpResponseMessage response = await httpClient.PostAsync(_url, content);
//var res = await response.Content.ReadAsAsync<T>();


}


}

解决方案 2:

            //send request
using (var httpClient = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
HttpResponseMessage response = await httpClient.PostAsync(_url, content);

}

解决方案 3:尝试导入证书,然后调用电话,但仍然无法正常工作。

const string certPath = @"C:\soaProdcer.cer";    
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
SslProtocols = System.Security.Authentication.SslProtocols.Tls
};
handler.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(certPath));

//send request
using (var httpClient = new HttpClient(handler))
{
var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
HttpResponseMessage response = await httpClient.PostAsync(_url, content);

}

我使用 OpenSSL 获得了证书

>openssl s_client -showcerts -connect serversoa:443

No client certificate CA names sent
---
SSL handshake has read 774 bytes and written 493 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1
Cipher : RC4-SHA
Session-ID: 4E0F69C75B8F041101562F7E9B3EA349
Session-ID-ctx:
Master-Key: 61A916A9B8AF26281B5F7A0138DF5E4C2A4B83995E0B3FDD2274BAD0D8E3C2B5E98AA7CCB48A6543F6814C2540B18848
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1558979896
Timeout : 300 (sec)
Verify return code: 18 (self signed certificate)

我将证书导入到 IIS 服务器到受信任的根证书颁发机构。

最佳答案

我不记得 Microsoft 告诉你这件事的确切链接。您的上述解决方案适用于较旧的 asp.net 核心版本。这是我为我的项目实现的最新 ASP.NET Core 的解决方案。希望对您有所帮助。

services.AddHttpClient<IYourService, YourService>()
.ConfigurePrimaryHttpMessageHandler(sp => new HttpClientHandler
{
AllowAutoRedirect = false,
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true,
SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12
});

另请阅读有关 HttpClientFactory 的信息:https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

关于c# - 如何在 .net core 2.1 中忽略 SSL 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56330973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com