6

I got a Xamarin Forms project and inside the MainPage.xaml.cs file i want to perform a request to my server. The server is written in ASP.NET Core 2 and is running with a self-signed certificate.

To buy a certificate isn't a solution for my problem, because customers don't want it and application only running in LAN.

In my MainPage.xaml.cs file the Http-request looks like this:

HttpClient m_Client = new HttpClient();
var uri = new Uri(myURL);

var response = await m_Client.GetAsync(uri);

if (response.IsSuccessStatusCode)
{
    ...
}

So far so good. If I bring the app on Android and try to perform the request, Android throws a SSL Exception for not finding a CA for my certificate.

How can I communicate with my server using a self-signed certificate?

I looked up the problem and find a lot of solutions like:

ServicePointManager
        .ServerCertificateValidationCallback +=
        (sender, cert, chain, sslPolicyErrors) => true;

If you add this code to your MainActivity.cs file in your Android project, it should accept all certificates. But that is not working for me. It seems like this method never gets called.

Any suggestions how to make the communication happen?

Regards

Klatschen
  • 1,652
  • 19
  • 32
  • 1
    It doesn't answer your question but how about disabling HTTPS? https://stackoverflow.com/questions/50935730/asp-net-core-2-1-kestrel-how-to-disable-https – CSharpRocks Sep 21 '18 at 11:44
  • @CSharpRocks Yes that would be my very last option :) – Klatschen Sep 21 '18 at 11:46
  • 1
    You can obtain SSL certs for free from some Certificate Authorities: just one example: https://letsencrypt.org – SushiHangover Sep 21 '18 at 14:00
  • @SushiHangover Yes, but didn't I have to enter something like a domain name? I don't have such, the server runs at local area network.. – Klatschen Sep 21 '18 at 14:08

1 Answers1

6

One option is to work on the certificate, which has been discussed in the comments above.

However, I think an option to ignore the certificate validation in code is always faster, and you just need this,

var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
HttpClient client = new HttpClient(handler);

For some unknown reasons, you cannot use the global event handler of ServicePointManager.ServerCertificateValidationCallback like you discovered, but HttpClient has its own handler.

Lex Li
  • 60,503
  • 9
  • 116
  • 147