I have a class library to perform Rest API calls built in 4.6.1 framework. I have used System.Net.Http V4 HttpClient for managing calls. This library works in normal dotnet apps. Recently I tried it for a DotNet Core app, it failed with security error. Later I modified library as suggested in post. It had some progress but the app fails with error as shown below
Error message: An error occurred while sending the request. Innerexception message: A security error occurred. StackTrace: at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Threading.Tasks.RendezvousAwaitable`1.GetResult() at System.Net.Http.WinHttpHandler.d__105.MoveNext()
Library Code:
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);
}
}
Please let me know, what needs to be done for this library to run for DotNet Core apps. Thanks.