I agree with Steve. You have a URL relay that performs 301 redirects, but for each image that the page requires, the browser still first contacts the server to find that it is 301 redirected to the CDN address. The only thing you save at this point is loading the content.
Instead, you can simply put the response filter in place to change the URLs of these assets before sending the response to client-client. Thus, the client browser should never make any calls to your server for static assets:
protected override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.RequestContext.HttpContext.Response.Filter = new CdnResponseFilter(filterContext.RequestContext.HttpContext.Response.Filter); }
And then CdnResponseFilter:
public class CdnResponseFilter : MemoryStream { private Stream Stream { get; set; } public CdnResponseFilter(Stream stream) { Stream = stream; } public override void Write(byte[] buffer, int offset, int count) { var data = new byte[count]; Buffer.BlockCopy(buffer, offset, data, 0, count); string html = Encoding.Default.GetString(buffer); html = Regex.Replace(html, "src=\"/Content/([^\"]+)\"", FixUrl, RegexOptions.IgnoreCase); html = Regex.Replace(html, "href=\"/Content/([^\"]+)\"", FixUrl, RegexOptions.IgnoreCase); byte[] outData = Encoding.Default.GetBytes(html); Stream.Write(outData, 0, outData.GetLength(0)); } private static string FixUrl(Match match) {
As a result, all content assets that look like <img src="\Content\whatever.jpg" /> will be converted to <img src="cdn-url.com\Content\whatever.jpg" />
Mike richards
source share