我需要对我网站上的所有图像使用 CDN。 所以,我决定使用 IIS Url 重写模块, 因为手动编辑我的所有网站 View - 这对我来说是不可能的。
所以我为IIS制定了规则,例如:
<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 来替换图像 URL?
请告知,如何使用 CDN 处理图像,不编辑我的 View 并避免重定向?
任何帮助将不胜感激
最佳答案
我同意史蒂夫的观点。您让 URL 重写器执行 301 重定向,但对于页面需要的每个图像,浏览器仍然首先向服务器发出请求,以发现它被 301 重定向到 CDN Url。此时您唯一要保存的是内容的下载。
您可以不这样做,只需放置一个响应过滤器,该过滤器将在将响应发送到客户端浏览器之前修改 Assets 的 URL。这样,客户端浏览器就不必为静态资源调用您的服务器:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.Filter = new CdnResponseFilter(filterContext.RequestContext.HttpContext.Response.Filter);
}
然后是 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
}
}
这样做的结果是所有看起来像 <img src="\Content\whatever.jpg" />
的内容 Assets 将转换为<img src="cdn-url.com\Content\whatever.jpg" />
关于asp.net-mvc-3 - 将图像放在 CDN 上,在 IIS7 上使用 MVC3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6892646/