Dealing With Broken Images In ASP.NET

Regardless of any site you have worked on, there is always a potential problem of a page rendering broken images. This is more likely to happen when images are served from external sources or through accidental deletion within content management platforms.

The only way I found a way to deal with this issue, is to provide a fallback alternative if the image to be served cannot be found. I've created a FallbackImage() extension method that can be applied to any string variable that contains a path to an image.

public static class ImageExtensions
{
    /// <summary>
    /// Creates a fallback image if the image requested does not exist.
    /// </summary>
    /// <param name="imageUrl"></param>
    /// <returns></returns>
    public static string FallbackImage(this string imageUrl)
    {
        string cachedImagePath = CacheEngine.Get<string>(imageUrl);

        if (string.IsNullOrEmpty(cachedImagePath))
        {
            string sanitiseImageUrl = string.Empty;

            if (!imageUrl.IsExternalLink())
                sanitiseImageUrl = $"{HttpContext.Current.GetCurrentDomain()}{imageUrl.Replace("~", string.Empty)}";

            // Attempt to request the image.
            WebRequest request = WebRequest.Create(sanitiseImageUrl);

            try
            {
                WebResponse response = request.GetResponse();
                cachedImagePath = imageUrl;
            }
            catch (Exception ex)
            {
                cachedImagePath = "/resources/images/placeholder.jpg";
            }

            // Add image path to cache.
            CacheEngine.Add(cachedImagePath, imageUrl, 5);
        }

        return cachedImagePath;
    }
}

To ensure optimum performance to minimise any unnecessary checks for the same image, the request is stored in cache for 5 minutes.

The method is using some functionality that I have developed within my own website, which will only work when referenced in your own codebase:

  • GetCurrentDomain - get the full URL of the current domain including any protocols and ports.
  • CacheEngine - provides a bunch of helper methods to interact with .NET cache provider easily.