d03*_*090 5 c# client-certificates x509certificate2 .net-core flurl
我需要向我的 Web 请求添加一个客户端证书并尝试以这种方式实现它: Stackoverflow
在此答案的末尾,介绍了“FlurlClient 方式”。使用和配置 FlurlClient 而不是全局 FlurlHttp 配置。我试过这个,但没有用。
我创建了一个新的.NET Core控制台应用程序来向您展示问题:
static void Main(string[] args)
{
/****** NOT WORKING *******/
try
{
IFlurlClient fc1 = new FlurlClient(url)
.ConfigureClient(c => c.HttpClientFactory = new X509HttpFactory(GetCert()));
fc1.WithHeader("User-Agent", userAgent)
.WithHeader("Accept-Language", locale);
dynamic ret1 = fc1.Url.AppendPathSegments(pathSegments).GetJsonAsync()
.GetAwaiter().GetResult();
}
catch
{
// --> Exception: 403 FORBIDDEN
}
/****** NOT WORKING *******/
try
{
IFlurlClient fc2 = new FlurlClient(url);
fc2.Settings.HttpClientFactory = new X509HttpFactory(GetCert());
fc2.WithHeader("User-Agent", userAgent)
.WithHeader("Accept-Language", locale);
dynamic ret2 = fc2.Url.AppendPathSegments(pathSegments).GetJsonAsync()
.GetAwaiter().GetResult();
}
catch
{
// --> Exception: 403 FORBIDDEN
}
/****** WORKING *******/
FlurlHttp.Configure(c =>
{
c.HttpClientFactory = new X509HttpFactory(GetCert());
});
dynamic ret = url.AppendPathSegments(pathSegments).GetJsonAsync()
.GetAwaiter().GetResult();
// --> OK
}
Run Code Online (Sandbox Code Playgroud)
在X509HttpFactory从链接StackOverflow的答案复制(但使用HttpClientHandler代替WebRequestHandler):
public class X509HttpFactory : DefaultHttpClientFactory
{
private readonly X509Certificate2 _cert;
public X509HttpFactory(X509Certificate2 cert)
{
_cert = cert;
}
public override HttpMessageHandler CreateMessageHandler()
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(_cert);
return handler;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,使用全局 FlurlHttp 配置有效,而配置 FlurlClient 无效。为什么?
这一切都归结为您调用事物的顺序:
fc.Url返回一个Url对象,它只不过是一个字符串构建的东西。它不保留对FlurlClient. (这允许 Flurl 作为独立于 Flurl.Http 的 URL 构建库存在。)Url.AppendPathSegments返回 "this" Url。Url.GetJsonAsync是一个扩展方法,它首先创建一个FlurlClient,然后使用它与当前Url进行 HTTP 调用。如您所见,您fc在该流程的第 1 步中丢失了对该流程的引用。2种可能的解决方案:
1.先构建URL,然后流畅地添加HTTP位:
url
.AppendPathSegments(...)
.ConfigureClient(...)
.WithHeaders(...)
.GetJsonAsync();
Run Code Online (Sandbox Code Playgroud)
2. 或者,如果您想重用 FlurlClient,请使用 WithClient 将其“附加”到 URL:
var fc = new FlurlClient()
.ConfigureClient(...)
.WithHeaders(...);
url
.AppendPathSegments(...)
.WithClient(fc)
.GetJsonAsync();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1552 次 |
| 最近记录: |