接受Xamarin Android中的自签名证书 [英] Accept self-signed certificates in Xamarin Android

查看:108
本文介绍了接受Xamarin Android中的自签名证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Xamarin Forms 项目,并且在MainPage.xaml.cs文件中,我想对服务器执行请求.该服务器是用 ASP.NET Core 2编写的,并且正在使用自签名证书运行.

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.

购买证书不是解决我的问题的方法,因为客户不希望证书而且应用程序仅在LAN中运行.

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

在我的MainPage.xaml.cs文件中,Http请求如下所示:

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)
{
    ...
}

到目前为止,一切都很好.如果我将应用程序放在 Android 上并尝试执行请求,则Android会抛出SSL异常,原因是找不到我的证书的CA.

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;

如果将此代码添加到Android项目中的MainActivity.cs文件中,则它应接受所有证书.但这对我不起作用.看来这种方法永远不会被调用.

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?

致谢

推荐答案

可以使用一种方法处理证书,上面的注释中已对此进行了讨论.

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);

由于某些未知原因,您不能像发现的那样使用ServicePointManager.ServerCertificateValidationCallback的全局事件处理程序,但是HttpClient有其自己的处理程序.

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

这篇关于接受Xamarin Android中的自签名证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆