我同意史蒂夫。您有URL重寫器進行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" />
這正是我需要的,謝謝你和@Steve! – bogert
我可以問一下,我們應該在ASP MVC應用程序中放置這個響應過濾器? – DevMania
實際的響應過濾器類?只要控制器可以訪問該類,該類就可以駐留在項目中的任何位置。 –