时间: 2016/11/01 20:15:43
因为我的服务器是小水管,加载一个完整的网站往往需要很久,想加速网站加载速度,静态文件最好是分离出来,所有就想到了扩展UrlHelper,用来支持CDN加载文件。
以 jquery-1.11.0.min.js
为例,一般常用的有以下两种(我自己的情况)
@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
{
/// CSS cdn
///
///
///
///
///
public static string CdnCssContent(this UrlHelper helper, string contentPath)
{
return GetContent(helper, contentPath, "CSS");
}
/// JS cdn
///
///
///
///
///
public static string CdnJsContent(this UrlHelper helper, string contentPath)
{
return GetContent(helper, contentPath, "JS");
}
/// img cdn
///
///
///
///
///
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节点添加一下配置
直接在页面上@Url.CdnCssContent("") or @Url.CdnJsContent("") or @Url.CdnImgContent("") 即可,如图是我的页面引用
这里提一点,把回源地址设置为主站的地址,这样当cdn找不到文件的时候,会自动从主站拉取文件
建议把防盗链Referer给打开,并设置好
写得不好,请各位多多指教