使用 SSL 的 Xamarin.Forms Image.Source

Flo*_*ian 5 ssl image imagesource xamarin xamarin.forms

我正在使用一个在线商店来存储通过我们的应用程序上传的用户图像,并受 SSL 保护。上传工作一切顺利,因为我使用的是带有附加证书的 WebClient。但是,当我尝试使用 Xamarin.Forms.Image 组件(例如,源设置为“ https://blabla.com/upload/image123.jpg ”)时,图像无法在 Android 上加载。在 iOS 上,这是有效的,因为我有一个自定义的 NSUrlProtocol 来处理 SSL 连接。

var image = new Image();

//will use ImageLoaderSourceHandler 
image.Source = "https://blabla.com/upload/image123.jpg";
Run Code Online (Sandbox Code Playgroud)

对于 WebClient,我将 X509Certificate2(私钥和密码)附加到 HttpWebRequest.ClientCertificates 并且它可以工作。但我不知道如何向 ImageLoaderSourceHandler 背后的任何加载机制提供该证书。

我如何才能在 Android 上实现此功能?

Flo*_*ian 4

所以我最终设置了自己的 SecuredUriImageSource:

var image = new Image();

//will use SecuredImageLoaderSourceHandler  
image.Source = new SecuredUriImageSource ("https://blabla.com/upload/image123.jpg");
Run Code Online (Sandbox Code Playgroud)

它使用此自定义处理程序来加载图像,而 WebClientEx 将实际证书附加到连接。

[assembly: ExportImageSourceHandler(typeof(SecuredUriImageSource), typeof(SecuredImageLoaderSourceHandler))]
namespace Helpers
{
    public class SecuredUriImageSource : ImageSource 
    {
        public readonly UriImageSource UriImageSource = new UriImageSource();

        public static SecuredUriImageSource FromSecureUri(Uri uri)
        {
            var source = new SecuredUriImageSource ();

            source.UriImageSource.Uri = uri;

            return source;
        }
    }

    public class SecuredImageLoaderSourceHandler : IImageSourceHandler
    {
        public async Task<Bitmap> LoadImageAsync(ImageSource imagesource, Android.Content.Context context, CancellationToken cancelationToken = default(CancellationToken))
        {
            var imageLoader = imagesource as SecuredUriImageSource;

            if (imageLoader != null && imageLoader.UriImageSource.Uri != null)
            {
                var webClient = new WebExtensions.WebClientEx();
                var data = await webClient.DownloadDataTaskAsync(imageLoader.UriImageSource.Uri, cancelationToken).ConfigureAwait(false);
                using (var stream = new MemoryStream(data) )
                    return await BitmapFactory.DecodeStreamAsync(stream).ConfigureAwait(false);
            }

            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)