0

I'm trying to make some GETs to the Facebook rest api from an ASP.net core application, but I get every time an exception because the remote host closed the connection. I tried like fourty different solutions that I found in similar questions but none of them worked. I changed the security protocol to Tls 1.2 but still got the same issue; I also tried using web client instead of http client. Then I tought it might have been the proxy of my office but cUrl worked fine; using postman I didn't get any error (even with tsl set to 1.0). Another attempt was to try changing the keep-alive duration to avoid time-outs. Here's the code with the HttpClient:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
using (var httpClient = new HttpClient()){
  httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
  httpClient.DefaultRequestHeaders.Add("Keep-Alive", "3600");
  var request = new HttpRequestMessage(HttpMethod.Get,
            "https://graph.facebook.com/v10.0/me?fields=id%2Cemail%2Cfirst_name%2Clast_name&access_token=" + socialLoginModel.accessToken);
  request.Headers.Add("Accept", "application/json");
  request.Headers.Add("User-Agent", "BriQ");
  var response = await httpClient.SendAsync(request);
}

And here's the code with the WebClient:

using(var wb = new WebClient()){
  var response = wb.DownloadString("https://graph.facebook.com/v10.0/me?fields=id%2Cemail%2Cfirst_name%2Clast_name&access_token=" + socialLoginModel.accessToken);
}

I'm completely out of ideas. Maybe it's something really stupid that's causing the exception but I can't figure it out alone

Tito Tigi
  • 83
  • 1
  • 14

1 Answers1

2

I'm not sure about which exception that you exactly got.

But as far as I know, if you're using .NET Core and the problem is caused by the SSL/TLS handshake failure error, then, unfortunately, setting the ServicePointManager may not work...

Because the ServicePointManager only affects the HttpWebRequest which is the default implementation of HttpClient on .NET Framework. Starting with .NET Core 2.1, the SocketsHttpHandler provides the implementation used by HttpClient.

Hence, I suppose the way to fix the issue is handling the SocketsHttpHandler:

using (var handler = new SocketsHttpHandler())
{
    handler.SslOptions = new SslClientAuthenticationOptions{EnabledSslProtocols = SslProtocols.Tls12};
    using (var httpClient = new HttpClient(handler))
    {
    // your code
    }
}

Alternatively, if you prefer HttpClientHandler, you could do in this way:

using (var handler = new HttpClientHandler())
{
    httpClientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
    using (var httpClient = new HttpClient(handler))
    {
    // your code
    }
}

Refs:

Allen Chen
  • 228
  • 1
  • 8