AutoBundle in asp.net mvc 5

时间:2023-03-10 06:33:43
AutoBundle in asp.net mvc 5
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 = ; i < paths.Length; i++)
{
string path = paths[i];
if (path.StartsWith("~"))
{
path = path.Substring();
}
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;
}
}
}