ASP. NET MVC automatically compresses files and generates CDN references

Source: Internet
Author: User

Many sites are separated by static files. I recommend a way to handle static file separation.

BundleExtensions.cs
public static class Bundleextensions    {public        static string Version = "1.0.0";        public static string Scriptspath = "Cdn";        public static bundle Production (the This bundle bundle, String CDN, String root, String minified,            string full = "")        { C6/>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 = Cont Ext.            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))) {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;            Set the compressed resource storage path Bundleextensions.scriptspath = "Resource";            Make the suffix of the request era, in order to flush out the client's cache bundleextensions.version = "00001";            CDN Site Address 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/script S/common/tab.js "," ~/resource/scripts/common/collapse.js "," ~/resource/scripts/commo N/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")); }

This will generate a reference to the JS file under the CDN site.

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

Yes, there's a missing place out here.

HTTP://LOCALHOST/CDN site requires you to specify in IIS to your site resource, otherwise access to your JS file.

But what if the CDN site hangs up, let's continue:

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"));

This will generate the following JS application:

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

This way when the CDN site is hung up or can access to the JS file.

What does the CSS do next:

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 D OM 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 Stylebu        Ndle 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 Classna me = 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/cs                        S ""/> ");            }}}}}} return true; }} () ", bundle.            Cdnpath, fallback, ClassName, RuleName, Rulevalue);        return bundle; }    }

All right, let's find out for ourselves:) to work.
Many of the code is copied online, patchwork.

ASP. NET MVC automatically compresses files and generates CDN references

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.