views:

155

answers:

2

Just want to confirm that there is no way to extend or replace Html.Image functionality without writing a replacement function.

I want to write a function that will use Amazon's S3 service for hosting images.

The best approach I've come up with is a helper method Html.SmartImage which would check a configuration property to see if i wanted to go to Amazon or not. It may even check a database of files that are hosted remotely and only 'farm them out' if they are in that list.

I'll post what I have when I've done it - but curious about any 'outside the box' ideas.

A: 

No you are right, you need to create your own extension method to handle custom scenarios like this.

Nick Berardi
A: 

This is what I did - at least for now:

Search and replace:

 html.image("~

for

 Html.CDNImage("~

And then created a helper in a static class ImageExtensions :

public static string CDNImage(this HtmlHelper htmlHelper, string imageRelativeUrl)
        {
            return CDNImage(htmlHelper, imageRelativeUrl, null, null);
        }

        public static string CDNImage(this HtmlHelper htmlHelper, string imageRelativeUrl, object htmlAttributes)
        {
            return CDNImage(htmlHelper, imageRelativeUrl, null, htmlAttributes);

        }

        public static string CDNImage(this HtmlHelper htmlHelper, string imageRelativeUrl, string alt, object htmlAttributes)
        {
            string url = Regex.Replace(imageRelativeUrl, "~/content/", "http://s3.amazon.com/", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            return htmlHelper.Image(url, alt, htmlAttributes);

        }

Obviously I'm using s3.amazon.com as a placeholder here - you have to fill in the URL for your CDN whatever it is.

If required you can use some kind of configuration property to determine whether or not you actually do the replacement.

Simon_Weaver