我同意史蒂夫。您让 URL 重写器执行 301 重定向,但是对于页面需要的每个图像,浏览器仍然首先向服务器发出请求,以发现它是 301 重定向到 CDN Url。此时您唯一要保存的是下载内容。
而不是这样做,您可以只放置一个响应过滤器,该过滤器将在响应发送到客户端浏览器之前修改资产的 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" />
都将转换为<img src="cdn-url.com\Content\whatever.jpg" />