1

I am working with an asp.net mvc 4 application. I would like to set up my sites images to be rendered via a cdn.

Is there any mechanism within MVC to set up image paths resolving to a cdn? I want the cdn to be dynamic so I can configure it via app settings.

I have a couple ideas open to me

  • Use a Html Helper to resolve all images with a cdn. Only issue with this is that I use spring.net dependency injection and dont believe its straight forward to inject in to a static class
  • Create a attribute that I place on my controller that examines the html output from my views, use a regex to find all non resolved domains and resolve them. Concerned about performance on this
  • Create an action result that is returned from my view that does similar to my previous point.

Any ideas/tips on this?

amateur
  • 43,371
  • 65
  • 192
  • 320

1 Answers1

0

There are big issues when using CDN, especially on the CSS side of things.

Some ideas from here: http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

public static void RegisterBundles(BundleCollection bundles)
{
    //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
    //            "~/Scripts/jquery-{version}.js"));

    bundles.UseCdn = true;   //enable CDN support

    //add link to jquery on the CDN
    var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";

    bundles.Add(new ScriptBundle("~/bundles/jquery",
                jqueryCdnPath).Include(
                "~/Scripts/jquery-{version}.js"));

    // Code removed for clarity.
}


</footer>

        @Scripts.Render("~/bundles/jquery")

        <script type="text/javascript">
            if (typeof jQuery == 'undefined') {
                var e = document.createElement('script');
                e.src = '@Url.Content("~/Scripts/jquery-1.7.1.js")';
                e.type = 'text/javascript';
                document.getElementsByTagName("head")[0].appendChild(e);

            }
        </script> 

        @RenderSection("scripts", required: false)
    </body>
</html>

It gets complicated but can be done with a bit of effort.

A very good article on this too: http://ofps.oreilly.com/titles/9781449320317/ch_ClientOptimization.html

Hope some of this helps

The imgage path resolving is dealt with here: MVC4 StyleBundle not resolving images

In controller:

ViewBag.CDNPath= "http://thepathtomyddnserver";

In view:

<img src="@Html.Raw(@ViewBag.CDNPath)/logo1.png">

This is the easy bit?

Community
  • 1
  • 1
ShaunOReilly
  • 2,186
  • 22
  • 34