代码改变世界

AutoBundle in asp.net mvc 5

2015-08-15 01:20  蜡笔小旧  阅读(301)  评论(0编辑  收藏  举报
using System.Collections.Concurrent;
using System.Text;

namespace System.Web.Optimization
{
    public static class Script
    {
        private static readonly ConcurrentDictionary<string, string> Bundles = new ConcurrentDictionary<string, string>();

        public static IHtmlString Src(params string[] paths)
        {
            string bundlePath = RegisterBundles(paths);
            if (string.IsNullOrEmpty(bundlePath))
            {
                return RenderOrignal(paths);
            }
            return Scripts.RenderFormat(Scripts.DefaultTagFormat, bundlePath);
        }

        private static IHtmlString RenderOrignal(params string[] paths)
        {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < paths.Length; i++)
            {
                string path = paths[i];
                if (path.StartsWith("~"))
                {
                    path = path.Substring(1);
                }
                stringBuilder.AppendFormat(Scripts.DefaultTagFormat, path);
            }

            return (IHtmlString)new HtmlString(stringBuilder.ToString());
        }

        private static string RegisterBundles(params string[] paths)
        {
            string key = string.Join(null, paths);
            if (Bundles.ContainsKey(key))
            {
                string bundlePath;
                if (Bundles.TryGetValue(key, out bundlePath))
                {
                    return bundlePath;
                }
            }
            else
            {
                string bundlePath = "~/Scripts/" + Math.Abs(key.GetHashCode());
                var bundle = BundleTable.Bundles.GetBundleFor(bundlePath);
                if (bundle == null)
                {
                    var scriptBundle = new ScriptBundle(bundlePath);
                    scriptBundle.Include(paths);
                    BundleTable.Bundles.Add(scriptBundle);
                }
                if (Bundles.TryAdd(key, bundlePath))
                {
                    return bundlePath;
                }
            }
            return null;
        }
    }
}