忽略Xamarin.Forms SSL证书错误(PCL)忽略Xamarin.Forms SSL证书错

2019-05-12 02:02发布

有没有办法像在这里描述的做一些事情: https://stackoverflow.com/a/2675183但Xamarin.Forms PCL应用程序? 我使用的HttpClient连接到服务器。

Answer 1:

ServicePointManager不PCL定义,但在特定平台的类中定义。

ServicePointManager两个Xamarin.iOSXamarin.Android具有相同的使用。 你可以在你的平台项目中引用的任何类中。 然而 ,目前还没有这样的类,似乎没有办法的Windows Phone应用程序这样做。

例:

// Xamarin.Android

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        // You may use ServicePointManager here
        ServicePointManager
            .ServerCertificateValidationCallback +=
            (sender, cert, chain, sslPolicyErrors) => true;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());
    }
}

// Xamarin.iOS

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        ServicePointManager
            .ServerCertificateValidationCallback +=
            (sender, cert, chain, sslPolicyErrors) => true;

        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }
}


Answer 2:

如果你正在使用AndroidClientHandler ,您需要提供SSLSocketFactory和自定义实现HostnameVerifier禁用所有检查。 要做到这一点,你需要继承AndroidClientHandler并重写适当的方法。

internal class BypassHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
    public bool Verify(string hostname, ISSLSession session)
    {
        return true;
    }
}

internal class BypassSslValidationClientHandler : AndroidClientHandler
{
    protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
    {
        return SSLCertificateSocketFactory.GetInsecure(1000, null);
    }

    protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
    {
        return new BypassHostnameVerifier();
    }
}

然后

var handler = new BypassSslValidationClientHandler();
var httpClient = new System.Net.Http.HttpClient(handler);


文章来源: Ignore SSL certificate errors in Xamarin.Forms (PCL)