【发布时间】:2018-06-25 06:36:15
【问题描述】:
我有一个类库来执行 4.6.1 框架中内置的 Rest API 调用。我使用 System.Net.Http V4 HttpClient 来管理调用。该库适用于普通的 dotnet 应用程序。最近我尝试了一个 DotNet Core 应用程序,它因安全错误而失败。后来我按照post 中的建议修改了库。它取得了一些进展,但应用程序失败并出现错误,如下所示
错误消息:发送请求时出错。 内部异常消息:发生安全错误。 堆栈跟踪: 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Threading.Tasks.RendezvousAwaitable`1.GetResult() 在 System.Net.Http.WinHttpHandler.d__105.MoveNext()
库代码:
private readonly HttpClient _client = null;
private ICredentials somecred;
public Program()
{
HttpClientHandler clientHandler = new HttpClientHandler { Credentials = somecred, UseDefaultCredentials = false };
_client=new HttpClient(new MessageHandler(clientHandler, TimeSpan.FromSeconds(1), 1), false);
_client.Timeout = TimeSpan.FromSeconds(90);
_client.BaseAddress = new Uri("https://somedomain.com/");
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.Expect100Continue = true;
}
public async Task<IOperationResponse> GetData()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
using (HttpResponseMessage httpResponse =
await _client.SendAsync(new HttpRequestMessage(HttpMethod.Head, "api/getdata"), HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)
)
{
if (httpResponse != null) { ... }
}
}
internal class MessageHandler : DelegatingHandler
{
public MessageHandler(HttpMessageHandler innerHandler, TimeSpan retryInterval, int retryCount) : base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
//!! security error in below line
response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
请告诉我,该库需要做什么才能运行 DotNet Core 应用程序。谢谢。
【问题讨论】:
标签: .net-core httpclient