访问在Xamarin中定位Android的客户端证书的REST服务

问题描述 投票:0回答:1

有没有人知道实现访问REST服务的最佳方式,该服务在Xamarin中定位Android的客户端证书?我正在使用.NET Standard 2.0项目来共享代码。

我已经尝试过WebRequestHandler来添加证书,但mono似乎不支持这个,应用程序也不会运行。我也试过HttpClientHandler。

以下代码段:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
X509Certificate2 certificate = App.CertificateFile;

var handler = new WebRequestHandler
{
    ClientCertificateOptions = ClientCertificateOption.Manual
};

handler.ClientCertificates.Add(certificate);
var client = new HttpClient(handler);

有一个类似的问题发布在这里Using custom SSL client certificates System.Net.HttpClient on Mono ,但不久前,所以希望事情有所改善。如果通过控制台应用程序调用,我的代码可以从.Standard 2.0项目正常工作,但相同的代码在设备上不起作用。

c# android xamarin httpclient
1个回答
1
投票

你可以尝试AndroidClientHandlerProgramatically using androidClientHandler

AndroidClientHandler clientHandler = new AndroidClientHandler();
Java.Security.Cert.X509Certificate cert = null;
try
{
    CertificateFactory factory = CertificateFactory.GetInstance("X.509");
    using (var stream = Application.Context.Assets.Open("MyCert.pfx"))
    {
        cert = (Java.Security.Cert.X509Certificate)factory.GenerateCertificate(stream);
    }
    } catch (Exception e)
    {
        System.Console.WriteLine(e.Message);
    }
    if (clientHandler.TrustedCerts != null)
    {
        clientHandler.TrustedCerts.Add(cert);
    }
    else
    {
        clientHandler.TrustedCerts = new List<Certificate>();
        clientHandler.TrustedCerts.Add(cert);
    }
    HttpClient client = new HttpClient(clientHandler);

更新:

如果up代码不起作用,您可以尝试使用与Qazxswpoi相同的Android Native实现,但使用起来更灵活:

AndroidClientHandler
© www.soinside.com 2019 - 2024. All rights reserved.