目前,我在Flurl上工作,我试图联系https中的一个API (我在我的实验室)。因此证书无效,Flurl无法继续工作:/
以下是我的错误信息:
Unhandled Exception: System.AggregateException: One or more errors occurred. (Call failed. The SSL connection could not be established, see inner exception. POST https://IP/api/aaaLogin.json) ---> Flurl.Http.FlurlHttpException: Call failed. The SSL connection could not be established, see inner exception. POST https://IP/api/aaaLogin.json ---> 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.
在Flurl文档中,我们可以使用using Flurl.Http.Configuration;
并修改DefaultHttpClientFactory
,但是我不理解指定的跳过错误的元素。
在网上,我可以看到同样的情况:https://github.com/tmenier/Flurl/issues/365,你对这个问题有问题吗?
谢谢!
发布于 2018-12-21 13:24:02
最典型的方法是使用创建自定义工厂
public class UntrustedCertClientFactory : DefaultHttpClientFactory
{
public override HttpMessageHandler CreateMessageHandler() {
return new HttpClientHandler {
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
}
}
然后在应用程序启动的某个地方注册它:
FlurlHttp.ConfigureClient("https://theapi.com", cli =>
cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
默认情况下,Flurl在每个主机上重用相同的HttpClient
实例,因此配置这种方式意味着每次对theapi.com
的调用都将允许使用不受信任的证书。与将HttpClient
传递给FlurlClient
构造函数相比,这样做的优点是,它将此配置“放在一边”,并在您以更典型/较少详细的方式使用Flurl时工作:
await "https://theapi.com/endpoint".GetJsonAsync();
发布于 2018-12-20 19:55:42
下面是Flurl的设置,它可以处理不受信任的证书:
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain,
errors) => true;
HttpClient httpClient = new HttpClient(httpClientHandler);
httpClient.BaseAddress = new Uri("https://myaddress.com");
var flurlClient = new FlurlClient(httpClient);
var apiInfo = await flurlClient.Request("apiInfo").GetJsonAsync<ApiInfoDto>();
我创建了自定义HttpClientHandler,它接受ServerCertificateCustomValidationCallback
中的每个证书。当然,您可以在这个处理程序中使用其他逻辑。
更新:使用此设置的,您不能为"http://myadress.com/apiInfo".GetJsonAsync<ApiInfoDto>()
使用Flurl扩展(不能编写"http://myadress.com/apiInfo".GetJsonAsync<ApiInfoDto>()
。如上面所示,您必须创建Flurl客户端,并使用Flurl客户端进行调用,如我的代码所示。其用法与URL的Flurl扩展相同。
发布于 2021-07-28 11:48:40
接受任何证书的内联解决方案是:
var myString = await "https://some-server-with-an-invalid-cert.net"
.AppendPathSegment("/some-file.txt")
.WithClient(new FlurlClient(new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, cert, chain,
errors) => true
})))
.GetStringAsync();
使用WithClient()
,您可以传递配置与默认客户端不同的客户端。在某些情况下,您不希望更改默认客户端,而是应用属性,例如,证书验证仅适用于此特定情况。
https://stackoverflow.com/questions/53853081
复制相似问题