放在CDN的图像,在使用IIS7 MVC3 [英] Put images on CDN, using MVC3 on IIS7

查看:211
本文介绍了放在CDN的图像,在使用IIS7 MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用CDN为我的网站上的所有图像。
所以,我已经决定使用IIS URL重写模块,
因为手动编辑我的所有网站的观点 - 它不可能为我

I need to use CDN for all images on my site. So, Ive decided to use IIS Url-rewriting module, because edit manually all my site views - its impossible for me.

因此​​,香港专业教育学院取得了IIS的规则,例如:

So Ive made rules for IIS, eg:

<rule name="cdn1" stopProcessing="true">

   <match url="^Content/Images.*/(.*\.(png|jpeg|jpg|gif))$" />

   <action 
      type="Redirect" 
      url="http://c200001.r9.cf1.rackcdn.com/{ToLower:{R:1}}" 
      redirectType="Permanent" />

</rule>

它的工作,但你可以看到有重定向类型的使用(301永久)。
而且我认为它会影响网站性能。
也许是可以编辑的 Request.Output 以替换图片网址?

请建议,我怎么能使用CDN图像,不编辑我的意见,避免重定向?

Please advice, how can I use CDN for images, do not edit my views and avoid redirects?

任何帮助将AP preciated

Any help will be appreciated

推荐答案

我同意与史蒂夫。你有URL重写做301重定向,但对于每一个图像页面需要,浏览器仍然向服务器请求首次发现,它的301重定向到一个CDN网址。你在这一点上保存的唯一的事情是内容的下载。

I agree with Steve. You have the URL rewriter doing 301 redirects, but for every image the page needs, the browser still makes a request to the server first to discover that it's 301 redirected to a CDN Url. The only thing you're saving at this point is the downloading of the content.

而不是这样做的,你可以把一个响应滤波器到位之前,响应发送到客户端浏览器将修改资产的URL。这样,客户端浏览器从来没有对您的服务器的静态资产的任何电话:

Instead of doing that, you can just put a response filter in place that will modify the URLs of the assets before the Response is sent to the client browser. That way, the client browser never has to 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);
}

和则CdnResponseFilter:

And then the 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)
    {
        //However the Url should be replaced
    }
}

这样做的结果是,看起来像&LT所有内容资产; IMG SRC =\\内容\\ whatever.jpg/&GT; 将被转换为&LT; IMG SRC =cdn-url.com \\内容\\ whatever.jpg/&GT;

这篇关于放在CDN的图像,在使用IIS7 MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆