相关疑难解决方法(0)

绕过.net核心中的无效SSL证书

我正在开发一个需要连接到https站点的项目.每次连接时,我的代码都会抛出异常,因为该站点的证书来自不受信任的站点.有没有办法绕过证书检查.net核心http?

我在以前版本的.NET中看到了这段代码.我想我只需要这样的东西.

 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
Run Code Online (Sandbox Code Playgroud)

c# ssl ssl-certificate asp.net-core

67
推荐指数
9
解决办法
5万
查看次数

在默认注入的 IHttpClientFactory 中禁用 SSL 证书验证

在 Startup.cs 中我注入一个IHttpClientFactory服务:

services.AddHttpClient();
Run Code Online (Sandbox Code Playgroud)

然后我可以创建一个新的HttpClient通过

public MyClass(IHttpClientFactory httpClientFactory, IOptions<MyClassOptions> options)
{
    _httpClient = httpClientFactory.CreateClient();
    // ...
}
Run Code Online (Sandbox Code Playgroud)

MyClass进行一些 API 访问;基本 URL 在对象中传递options

为了进行测试,我设置了 API 的虚拟实例,它使用自签名 SSL 证书。不幸的是,该证书被(正确地)识别为无效:

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Run Code Online (Sandbox Code Playgroud)

如何在工厂层(即直接在ConfigureServices方法中)禁用证书验证?

我发现了这个问题,但它似乎使用了一些自定义HttpClient实现(?),而我想针对默认实现。以下不起作用(DI 选择了错误的构造函数并随后失败):

services.AddHttpClient<IMyClass, MyClass>();
Run Code Online (Sandbox Code Playgroud)

这个答案建议为配置提供一个名称HttpClient,但它传递了一些魔术字符串,我想避免这种情况(MyClass位于设计为也可供其他人使用的类库中)。不传递名称也不起作用,因为AddHttpClient那样只会返回一个IServiceCollection对象。

c# dependency-injection dotnet-httpclient asp.net-core

1
推荐指数
1
解决办法
6037
查看次数