How to configure FFImageLoading to visualize images from URL when a PROXY is configured.

FFImageLoading is a well-known library for those who develop applications using Xamarin Forms.

In particular, I use the CachedImage control that allows you to view images within pages.

I recently had a problem with an application that displays images from a URL, using a PROXY (specifically a PROXY PAC).

<ffimageloading:CachedImage             
  Aspect="AspectFill"             
  DownsampleToViewSize="True"                
  ErrorPlaceholder="image_error"              
  HorizontalOptions="Center"             
  LoadingPlaceholder="image_loading"             
  Source="{Binding ImageUrl}"             
  VerticalOptions="CenterAndExpand">         
</ffimageloading:CachedImage>

This code works fine without PROXY. When a PROXY is configured, the code returns an exception in the VS2019 output window (something like “FileNotFoundException” if I remember correctly).

After some tests, I have found this solution that must be implemented in Xamarin.Android project (I have not tried in other platforms).

Without PAC

In MainActivity.cs, OnCreate:

...
var handler = new HttpClientHandler
{
  Proxy = GetProxySettings()
};

var config = new FFImageLoading.Config.Configuration()
{
  HttpClient = new System.Net.Http.HttpClient(handler)
};
ImageService.Instance.Initialize(config);

...

global::Xamarin.Forms.Forms.Init(this, bundle); 
CachedImageRenderer.Init(true);        
CachedImageRenderer.InitImageViewHandler();

Where, GetProxySettings() is:

public WebProxy GetProxySettings()
{
    var proxyHost = "myproxy.xxx.net"; 
    var proxyPort = "8080"; 

    return !string.IsNullOrEmpty(proxyHost) && !string.IsNullOrEmpty(proxyPort)             
    ? new WebProxy($"{proxyHost}:{proxyPort}")
    : null;     
}

In this case, you have to know the PROXY HOST and PORT.

WITH PAC

With a PROXY PAC, there is not a PROXY HOST defined because it is dynamic. So, you can use this code in your MainActivity.cs:

...

IWebProxy webProxy = WebRequest.GetSystemWebProxy();

var handler = new HttpClientHandler
{
  Proxy = webProxy
};

var config = new FFImageLoading.Config.Configuration()
{
  HttpClient = new System.Net.Http.HttpClient(handler)
};
ImageService.Instance.Initialize(config);

...

global::Xamarin.Forms.Forms.Init(this, bundle);         
CachedImageRenderer.Init(true);         
CachedImageRenderer.InitImageViewHandler();

Is it possible to use the PROXY configuration defined on the device with WebRequest.GetSystemWebProxy();

Pubblicità

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...