根据我之前阅读的 Scott Guthrie 的一篇文章和Mads Kristensen 发布的视频,我应该能够通过替换以下内容在 ASP.net MVC 4 中自动捆绑/缩小:
<link href="Styles/reset.css" rel="stylesheet" type="text/css" />
<link href="Styles/normalize.css" rel="stylesheet" type="text/css" />
<link href="Styles/styles.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-validation.min.js" type="text/javascript"></script>
有了这个:
<link href="Styles/css" rel="stylesheet" type="text/css" />
<script src="Scripts/js" type="text/javascript"></script>
我尝试同时针对 .Net 4.0 和 4.5,但似乎没有什么不同。我收到 404 错误,并且链接和脚本标签永远不会指向捆绑的资源。
此功能是否已从最终版本中删除?
我想将此功能用于“主题”。
这就是我最终实施的方式。希望这是有道理的...
/// <summary>
/// Render stylesheets HTML for the given theme. Utilizes System.Web.Optimization for bundling and minification
/// </summary>
/// <param name="themeName">Name of theme</param>
/// <returns>HtmlString containing link elements</returns>
public static IHtmlString RenderThemeStyles(string themeName)
{
IHtmlString retValue = null;
// If no theme name is passed, return null
if (!themeName.HasValue())
return retValue;
var ctxt = HttpContext.Current;
string themePath = "~/Themes/" + themeName;
string themeKey = themePath + "/css";
if (ctxt.Cache[themeKey] != null)
return (IHtmlString)ctxt.Cache[themeKey];
// Check to see if the theme directory exists. Throw error if it does not
string themeSysPath = HttpContext.Current.Server.MapPath(themePath);
DirectoryInfo themeDir = new DirectoryInfo(themeSysPath);
if (!themeDir.Exists)
throw new ApplicationException(string.Format("Theme directory \"{0}\" does not exist", themePath));
// Remove the old bundle if it already exists
var old_bundle = BundleTable.Bundles.FirstOrDefault(b => b.Path == themeKey);
if (old_bundle != null)
BundleTable.Bundles.Remove(old_bundle);
if (themeDir.GetFiles("*.css").Length > 0)
{
// If there are css files, add them to the bundler and save the rendered output to cache
Bundle styles = new StyleBundle(themeKey).IncludeDirectory(themePath, "*.css");
BundleTable.Bundles.Add(styles);
retValue = Styles.Render(themeKey);
ctxt.Cache.Insert(themeKey, retValue, new System.Web.Caching.CacheDependency(themeSysPath));
}
else
{
// If there are no css files, save empty string to cache
ctxt.Cache.Insert(themeKey, new HtmlString(string.Empty), new System.Web.Caching.CacheDependency(themeSysPath));
}
return retValue;
}