asp.net mvc自動壓縮文件,並生成CDN引用

来源:http://www.cnblogs.com/Innovate/archive/2016/05/06/5465287.html
-Advertisement-
Play Games

ScriptsBundleTransform.cs BundleConfig.cs 這樣的話就能生成 CDN 站點下的JS文件引用了 對了這裡漏掉了一個地方, 但是如果CDN站點掛掉了怎麼辦,咱們繼續: SctiptsBundleExtensions.cs 這樣會生成如下的JS應用: 這樣的話當CD ...


很多站點都是用了靜態文件分離。我推薦一種處理靜態文件分離的方式。

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;
        }
    }

 

好吧後面的大家自己摸索吧:)上班了
很多代碼是網上抄襲的,東拼西湊。

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Github開源聲明 本網站的代碼開源,開源的目的如下 技術分享 希望業內同行貢獻代碼 希望能夠讓網站更加安全 開源地址: "CodeSnippet開源地址" 關於代碼貢獻 任何人都可以貢獻代碼,一般在 1 3個工作日內會確認合併 代碼請進行測試後提交。 現在需要如下的代碼貢獻 移動端自適應和響應式 ...
  • WCF的宿主可以是 Windows 服務、COM+應用程式、WAS(Windows Activation Services,Windows進程激活服務)或IIS、Windows應用程式,或簡單的控制台應用程式及任何.net程式。 ...
  • 做了1年多了C#,發現些項目過程中很多基礎東西都不是很清晰,基礎不夠牢固。現在開始複習基礎知識並做重點記錄 方法需要被重寫的時候,可以在方法前加入virtual使方法變成虛方法。 這樣我們可以重新寫個方法對虛方法進行重寫需要加上override。 註意:成員欄位和靜態函數都不能聲明為virtual, ...
  • 回到目錄 多看幾篇 之所以寫這篇文章完全是因為最近在研究FastDFS這個分散式的文件存儲系統,當然這不是我第一次研究它了,就像我們去看一本書,我們不會只看一篇,而是一次次,一篇篇,每看一次會有新的收穫,而研究技術,框架也是一樣,每研究一次,同樣會有不同層次的收穫,這次主要把fastDFS的集群就配 ...
  • 一些項目中,會涉及到事務的寫法,比如訂單相關,訂單成功,會涉及到產品的庫存和賬戶金額的一些信息變動,當然,如果整個流程成功,那是沒什麼問題,關鍵是如果中間某一步驟出現bug了,那之前已執行的一些變動就要回滾回去,所以就不可避免的用到事務的寫法。以前只是在資料庫中會涉及到事務寫法 最近做一些財務方面的 ...
  • 可以在 程式包管理器控制臺中輸入PM> Install-Package NPOI會下載最新版本NPOI----------------------------引用了NPOI-------------------------------- public static void Export() { s... ...
  • C#
    泛型:通過參數化類型來實現在同一份代碼上操作多種數據類型。利用“參數化類型”將類型抽象化,從而實現靈活的復用。 例子代碼: class Program { static void Main(string[] args) { ... ...
  • (譯者註:使用EF開發應用程式的一個難點就在於對其DbContext的生命周期管理,你的管理策略是否能很好的支持上層服務 使用獨立事務,使用嵌套事務,並行執行,非同步執行等需求? Mehdi El Gueddari對此做了深入研究和優秀的工作並且寫了一篇優秀的文章,現在我將其翻譯為中文分享給大家。由於 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...