我意识到这是一个老问题,但这里是 dprothero 答案的修改版本,它将嵌入捆绑包。创建一个静态 C# 类并将此方法放入其中:
public static IHtmlString EmbedCss(this HtmlHelper htmlHelper, string path)
{
try
{
// Get files from bundle
StyleBundle b = (StyleBundle)BundleTable.Bundles.GetBundleFor("~/Content/css");
BundleContext bc = new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, "~/Content/css");
List<BundleFile> files = b.EnumerateFiles(bc).ToList();
// Create string to return
string stylestring = "";
// Iterate files in bundle
foreach(BundleFile file in files)
{
// Get full path to file
string filepath = HttpContext.Current.Server.MapPath(file.IncludedVirtualPath);
// Read file text and append to style string
string filetext = File.ReadAllText(filepath);
stylestring += $"<!-- Style for {file.IncludedVirtualPath} -->\n<style>\n{filetext}\n</style>\n";
}
return htmlHelper.Raw(stylestring);
}
catch
{
// return nothing if we can't read the file for any reason
return null;
}
然后转到您要在其中使用它的任何视图。请务必添加 using 语句,以便您的视图可以看到 CSS 帮助器。我还使用 TempData 来决定是否内联渲染它:
<!-- Using statement -->
@using Namespace.Helpers;
<!-- Check tempdata flag for whether or not to render inline -->
@if (TempData["inlinecss"] != null)
{
<!-- Embed CSS with custom code -->
@Html.EmbedCss("~/Content/css")
}
else
{
<!-- Use links to reference CSS -->
@Styles.Render("~/Content/css")
}