Xamarin PCL为Android和IOS签署了自己的认证证书

时间:2017-09-07 11:56:01

标签: xamarin xamarin.ios xamarin.android ssl-certificate cross-platform

我试图将我的完整Rest服务从http传递给https。

我创建了一个自签名证书,我将它用于IIS Express。我在谷歌浏览器上验证它,它与邮递员完美配合。我的休息服务工作在http和https。

我使用PCL项目(​​IOS和Android)一切正常,http请求但我有https请求异常。异常消息为null。

我尝试直接从Visual Studio 2015创建测试证书,但在属性中禁用了该按钮 - >签名。

我还尝试将自签名证书安装为受信任的根,但我的模拟器和我的其余服务之间的通信没有成功。

我的代码

public partial class MainPage : ContentPage
{
    private string url = string.Empty;
    private HttpClient _client;


    public MainPage()
    {
        InitializeComponent();
        switch (Device.RuntimePlatform)
        {
            case Device.iOS:
                _client = new HttpClient(new NSUrlSessionHandler());
                break;
            case Device.Android:
                _client = new HttpClient();
                break;
        }
        _client = new HttpClient();
        test();


    }

    private async void test()
    {
        //url = "http://192.168.1.106:9630/PrototypeB.svc/Test";
        url = "https://192.168.1.106:44301/PrototypeB.svc/Test";
        try
        {
            var _content = await _client.GetStringAsync(url);
            List<Test> _posts = JsonConvert.DeserializeObject<List<Test>>(_content);
        }
        catch (HttpRequestException e)
        {
            string test = e.Message;
        }
        catch (Exception e)
        {
            string test = e.Message;
        }
    }
}

如何使用https和自签名证书与我的Android和IOS模拟器进行通信?

1 个答案:

答案 0 :(得分:-2)

您可以使用 ServicePointManager 忽略证书验证检查。

执行iOS和Android平台中的代码,如下所示:

System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => { 
                         return true; 
                     };

参考文献:

此外,ModernHttpClient Pro提供此功能,但它不是免费的。