很多站点都是用了静态文件分离。我推荐一种处理静态文件分离的方式。

BundleExtensions.cs
 public static class BundleExtensions    {        public static string Version = "1.0.0";        public static string ScriptsPath = "Cdn";        public static Bundle Production(this Bundle bundle, string cdn, string root, string minified,            string full = "")        {            var transform = new ScriptsBundleTransform()            {                Version = Version,                ScriptsPath = System.IO.Path.Combine("~/", ScriptsPath, root),                Minified = minified,                Full = full            };            bundle.Transforms.Add(transform);            bundle.CdnPath = cdn + "/" + root + "/" + string.Format("{0}?{1}", minified, Version);            return bundle;        }    }

ScriptsBundleTransform.cs

public class ScriptsBundleTransform : IBundleTransform    {        public string ScriptsPath { get; set; }        public string Version { get; set; }        public string Minified { get; set; }        public string Full { get; set; }        public ScriptsBundleTransform()        {        }        public ScriptsBundleTransform(string path, string version, string minified, string full)        {            ScriptsPath = path;            Version = version;            Minified = minified;            Full = full;        }        public void Process(BundleContext context, BundleResponse response)        {            string scriptsRoot = context.HttpContext.Server.MapPath(ScriptsPath);            if (!Directory.Exists(scriptsRoot))                Directory.CreateDirectory(scriptsRoot);            //  if minified file name specified...            if (!string.IsNullOrEmpty(Minified))            {                using (TextWriter writer = File.CreateText(Path.Combine(scriptsRoot, Minified)))                {                    writer.Write(response.Content);                }            }            //  if full file name specified...            if (!string.IsNullOrEmpty(Full))            {                using (Stream writer = File.OpenWrite(Path.Combine(scriptsRoot, Full)))                {                    foreach (var file in response.Files)                    {                        file.VirtualFile.Open().CopyTo(writer);                    }                }            }        }    }

BundleConfig.cs

        public static void RegisterBundles(BundleCollection bundles)        {            bundles.UseCdn = true;            BundleTable.EnableOptimizations = true;            //制定压缩后的资源存储路径            BundleExtensions.ScriptsPath = "Resource";            //制定请求时代的后缀,为了刷新掉客户端的缓存            BundleExtensions.Version = "00001";            //CDN站点地址            const string ajaxCdnPath = "http://localhost/Cdn";            bundles.Add(new ScriptBundle("~/bundles/bootstrap")                .IncludeFallback("$.fn.affix",                    "~/Resource/Scripts/common/transition.js",                    "~/Resource/Scripts/common/button.js",                    "~/Resource/Scripts/common/affix.js",                    "~/Resource/Scripts/common/tab.js",                    "~/Resource/Scripts/common/collapse.js",                    "~/Resource/Scripts/common/tooltip.js",                    "~/Resource/Scripts/common/respond.js")                .Production(ajaxCdnPath, "Scripts", "bootstrap.mincdn.js", "bootstrap.src.js"));            bundles.Add(new ScriptBundle("~/Content/bootstrap")                .Include("~/Resource/Content/bootstrap.css")                .Include("~/Resource/Content/common/button.css")                .Include("~/Resource/Content/common/bootstrap-theme.css")                .Production(ajaxCdnPath, "Content", "bootstrap.mincdn.css", "bootstrap.src.css"));        }

这样的话就能生成 CDN 站点下的JS文件引用了

<script src="http://localhost/Cdn/Scripts/bootstrap.mincdn.js?00001"></script>

对了这里漏掉了一个地方,

http://localhost/Cdn站点需要你在IIS中指定到你站点的Resource下,不然访问不到你的JS文件。

但是如果CDN站点挂掉了怎么办,咱们继续:

SctiptsBundleExtensions.cs

    public static class SctiptsBundleExtensions    {        public static ScriptBundle IncludeFallback(this ScriptBundle bundle, string cdnFallbackExpression,            string virtualPath, params IItemTransform[] transforms)        {            bundle.CdnFallbackExpression = cdnFallbackExpression;            bundle.Include(virtualPath, transforms);            return bundle;        }        public static ScriptBundle IncludeFallback(this ScriptBundle bundle, string cdnFallbackExpression,          params string[] virtualPaths)        {            bundle.CdnFallbackExpression = cdnFallbackExpression;            bundle.Include(virtualPaths);            return bundle;        }    }
        bundles.Add(new ScriptBundle("~/bundles/jquery")                .IncludeFallback("window.jQuery", "~/Resource/Scripts/common/jquery-{version}.js")                .Production(ajaxCdnPath, "Scripts", "jquery.mincdn.js", "jquery.src.js"));

这样会生成如下的JS应用:

<script src="http://localhost/Cdn/Scripts/jquery.mincdn.js?00001"></script><script>(window.jQuery)||document.write('<script src="/dome/bundles/jquery"><//script>');</script>

这样的话当CDN站点挂掉了还是能够访问到JS文件的。

接下来CSS怎么处理呢:

StyleBundleExtensions.cs

 public static class StyleBundleExtensions    {        /// <summary>        /// Include a stylesheet to fallback to when external CdnPath does not load.        /// </summary>        /// <param name="bundle"></param>        /// <param name="fallback">Virtual path to fallback stylesheet</param>        /// <param name="className">Stylesheet class name applied to test DOM element</param>        /// <param name="ruleName">Rule name to test when the class is applied ie. width</param>        /// <param name="ruleValue">Value to test when the class is applied ie. 1px</param>        /// <returns></returns>        public static StyleBundle IncludeFallback(this StyleBundle bundle, string fallback,            string className = null, string ruleName = null, string ruleValue = null)        {            if (String.IsNullOrEmpty(bundle.CdnPath))            {                throw new Exception("CdnPath must be provided when specifying a fallback");            }            if (VirtualPathUtility.IsAppRelative(bundle.CdnPath))            {                bundle.CdnFallbackExpress(fallback);            }            else if (new[] { className, ruleName, ruleValue }.Any(String.IsNullOrEmpty))            {                throw new Exception(                    "IncludeFallback for cross-domain CdnPath must provide values for parameters [className, ruleName, ruleValue].");            }            else            {                bundle.CdnFallbackExpress(fallback, className, ruleName, ruleValue);            }            return bundle;        }        private static StyleBundle CdnFallbackExpress(this StyleBundle bundle, string fallback,            string className = null, string ruleName = null, string ruleValue = null)        {            bundle.Include(fallback);            fallback = VirtualPathUtility.ToAbsolute(fallback);            bundle.CdnFallbackExpression = String.IsNullOrEmpty(className) ?                String.Format(@"function() {{                var len = document.styleSheets.length;                for (var i = 0; i < len; i++) {{                    var sheet = document.styleSheets[i];                    if (sheet.href.indexOf('{0}') !== -1) {{                        var rules = sheet.rules || sheet.cssRules;                        if (rules.length <= 0) {{                            document.write('<link href=""{1}"" rel=""stylesheet"" type=""text/css"" />');                        }}                    }}                }}                return true;                }}()", bundle.CdnPath, fallback) :                String.Format(@"function() {{                var loadFallback,                    len = document.styleSheets.length;                for (var i = 0; i < len; i++) {{                    var sheet = document.styleSheets[i];                    if (sheet.href.indexOf('{0}') !== -1) {{                        var meta = document.createElement('meta');                        meta.className = '{2}';                        document.head.appendChild(meta);                        var value = window.getComputedStyle(meta).getPropertyValue('{3}');                        document.head.removeChild(meta);                        if (value !== '{4}') {{                            document.write('<link href=""{1}"" rel=""stylesheet"" type=""text/css"" />');                        }}                    }}                }}                return true;            }}()", bundle.CdnPath, fallback, className, ruleName, ruleValue);            return bundle;        }    }
好吧后面的大家自己摸索吧:)上班了
很多代码是网上抄袭的,东拼西凑。

asp.net mvc自动压缩文件,并生成CDN引用的更多相关文章

  1. ASP.NET MVC 5 学习教程:生成的代码详解

    原文 ASP.NET MVC 5 学习教程:生成的代码详解 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 创建连接字符串 ...

  2. [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传

    原文 [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传 Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件 ...

  3. ASP.NET MVC 导出CSV文件

    ASP.NET MVC   导出CSV文件.直接贴代码 /// <summary> /// ASP.NET MVC导出CSV文件Demo1 /// </summary> /// ...

  4. Asp.Net Mvc自定义控件之树形结构数据生成表格 - WPF特工队内部资料

    最近项目中有一个需求,将树形结构的数据,以表格的形式展示在页面中,下图是最终呈现效果: 源码: @{ Layout = null; } <!DOCTYPE html> <html&g ...

  5. Asp.Net MVC 文件管理Demo(文件展示,上传,下载,压缩,文件重命名等)

    之前 ,有想做一个文件管理页面. 参考了 许多资料,终于完成了一个基于Asp.net MVC 的文件管理Demo.界面如下.   一,实现功能及相关技术 文件管理Demo基于Asp.NET MVC , ...

  6. ASP.NET MVC下使用文件上传

    这里我通过使用uploadify组件来实现异步无刷新多文件上传功能. 1.首先下载组件包uploadify,我这里使用的版本是3.1 2.下载后解压,将组件包拷贝到MVC项目中 3.  根目录下添加新 ...

  7. ASP.NET MVC实现Excel文件的上传下载

    在应用系统开发当中,文件的上传和下载是非常普遍的需求.在基于.NET的C/S架构的项目开发当中,有多种方案可以实现文件的上传和下载(httpwebrequest.webclient等),而且多采用异步 ...

  8. asp.net MVC 自动下载apk

    在Asp.net MVC中直接把.apk文件放入/Upload/App/ 路径下,然后通过IIS发布完之后,再通过http://xxx/Upload/App/xx.apk访问是访问不到的,因此不能下载 ...

  9. 用Fine Uploader+ASP.NET MVC实现ajax文件上传[代码示例]

    Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件的 Javascript 组件. This project attempts to achi ...

随机推荐

  1. SQL SERVER 常见SQL和函数使用

    一.语法 参考原文:https://blog.csdn.net/xushaozhang/article/details/55053037 1.查询插入 (1)SELECT INTO 语句格式: Ora ...

  2. C++ 三/五法则

    当定义一个类时,我们显式地或隐式地指定了此类型的对象在拷贝.赋值和销毁时做什么.一个类通过定义三种特殊的成员函数来控制这些操作:拷贝构造函数.拷贝赋值运算符和析构函数. 拷贝构造函数定义了当用同类型的 ...

  3. python beautifulsoup爬虫学习

    BeautifulSoup(page_html, "lxml").select(),这里可以通过浏览器开发者模式选择copy selector,并且并不需要完整路径. github ...

  4. VI和VIM

    linux下vi.VIM命令大全   进入vi的命令 vi filename :打开或新建文件,并将光标置于第一行首 vi +n filename :打开文件,并将光标置于第n行首 vi + file ...

  5. python学习第42、43天 HTML\CSS

    前端是什么? 帮助不了解后端程序的客户轻松使用程序的工具,可以提升工作效率,提供各种各样的体验. 通用的前端大致会使用三种语言,用在三个不同的方面对前端进行架构和优化,这里也只介绍这三种 web前端常 ...

  6. npm i 和 npm install 的区别

    实际使用的区别点主要如下(windows下): 1. 用npm i安装的模块无法用npm uninstall删除,用npm uninstall i才卸载掉 2. npm i会帮助检测与当前node版本 ...

  7. noj算法 装载问题 回溯法

    描述: 有两艘船,载重量分别是c1. c2,n个集装箱,重量是wi (i=1…n),且所有集装箱的总重量不超过c1+c2.确定是否有可能将所有集装箱全部装入两艘船. 输入: 多个测例,每个测例的输入占 ...

  8. 基于AD5663的UV灯电压控制

    在开发臭氧发生器的时,我们使用UV灯来实现臭氧的产生.而UV灯的强度决定了臭氧产生的浓度,UV灯的光强则与其控制电压密切相关.所以我们要控制产生的臭氧的浓度就需要调节其控制电压.我们选择了AD5663 ...

  9. 整理oracle 树形查询

    注:本文参考了<整理oracle 树形查询> sql树形递归查询是数据库查询的一种特殊情形,也是组织结构.行政区划查询的一种最常用的的情形之一.下面对该种查询进行一些总结: create ...

  10. Confluence 6 针对 key "cp_" 或 "cps_" 的 "Duplicate Entry" 问题解决

    如果你遇到了下面的错误信息,例如: com.atlassian.confluence.importexport.ImportExportException: Unable to complete im ...