因為我的服務器是小水管,加載一個完整的網站往往需要很久,想加速網站加載速度,靜態文件最好是分離出來,所有就想到了擴展UrlHelper,用來支持CDN加載文件。
以 jquery-1.11.0.min.js 為例,一般常用的有以下兩種(我自己的情況)
<script src="~/Content/themes/plugins/jQuery/jquery-1.11.0.min.js"></script>
<script src="@Url.Content("~/Content/themes/plugins/jQuery/jquery-1.11.0.min.js")"></script>
@Url.Content("") 形式是UrlHelper的方法,我們今天就來擴展它
新建一個UrlHelperExtensions 類
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Chenmo.Soft.WebUI.Framework
{
public static class UrlHelperExtensions
{
/// <summary>CSS cdn
///
/// </summary>
/// <param name="helper"></param>
/// <param name="contentPath"></param>
/// <returns></returns>
public static string CdnCssContent(this UrlHelper helper, string contentPath)
{
return GetContent(helper, contentPath, "CSS");
}
/// <summary>JS cdn
///
/// </summary>
/// <param name="helper"></param>
/// <param name="contentPath"></param>
/// <returns></returns>
public static string CdnJsContent(this UrlHelper helper, string contentPath)
{
return GetContent(helper, contentPath, "JS");
}
/// <summary>img cdn
///
/// </summary>
/// <param name="helper"></param>
/// <param name="contentPath"></param>
/// <returns></returns>
public static string CdnImgContent(this UrlHelper helper, string contentPath)
{
return GetContent(helper, contentPath, "IMG");
}
private static string GetContent(this UrlHelper helper, string contentPath, string type)
{
var result = helper.Content(contentPath);
if (ConfigurationManager.AppSettings[$"CDN_{type}_Enable"].ToUpper() == "TRUE")
{
result = ConfigurationManager.AppSettings[$"CDN_{type}_URL"]
+ contentPath.TrimStart('~');
}
return result;
}
}
}
同時在web.config 中的appSettings節點添加一下配置
<!--是否開啟CDN True False--> <add key="CDN_CSS_Enable" value="True" /> <add key="CDN_CSS_URL" value="http://css.static.ofnhkb1.com" /> <add key="CDN_JS_Enable" value="True" /> <add key="CDN_JS_URL" value="http://js.static.ofnhkb1.com" /> <add key="CDN_IMG_Enable" value="True" /> <add key="CDN_IMG_URL" value="http://img.static.ofnhkb1.com" />
直接在頁面上@Url.CdnCssContent("") or @Url.CdnJsContent("") or @Url.CdnImgContent("") 即可,如圖是我的頁面引用



這裡提一點,把回源地址設置為主站的地址,這樣當cdn找不到文件的時候,會自動從主站拉取文件
建議把防盜鏈Referer給打開,並設置好
寫得不好,請各位多多指教