如何在 ASP.NET Web 表单中呈现 CSS 内联

How To Render CSS Inline In ASP.NET Web Form

我正在使用 System.Web.Optimization 捆绑 css 和 script.But 现在我想呈现 css 和内联脚本而不是引用单个文件。

我正在尝试为 System.Web.Optimization.Render() 创建一个扩展方法,但我无法为该方法提供参数作为 HttpContextBase GenerateBundleResponse()

以下是我的错误代码

    public static class OptimizationStylesExtention
    {

      private static string GetBundleContent(HttpContextBase httpContextBase, 
        string bundleVirtualPath)
       {
            return BundleTable.Bundles
                .Single(b => b.Path == bundleVirtualPath)
                .GenerateBundleResponse(new BundleContext(httpContextBase, 
                            BundleTable.Bundles, bundleVirtualPath)).Content;
        }

    public static IHtmlString RenderInline(this HtmlString str, params string[] 
    bundleVirtualPath)
    {
        StringBuilder bundleContent = new StringBuilder();
        foreach (var virtualPath in bundleVirtualPath)
        {
            bundleContent.Append(BundleTable.Bundles.Single(b => b.Path == virtualPath)
            .GenerateBundleResponse(new BundleContext(str, BundleTable.Bundles, virtualPath)));
        }
        return new HtmlString(string.Format("{<style>{0}</style>}", bundleContent.ToString()));
    }
}

您好,您可以使用 GenerateBundleResponse 方法。 BundleResponseclass.

的方法是哪个

这是代码

using System.Web.Optimization;

/// <summary>
/// This is the extension for the bundle. 
/// Which is used when we want to use inline css with style tag
/// </summary>
public static class BundleExtensions
{
    /// <summary>
    /// Returns inline css with style tag
    /// </summary>
    /// <param name="VirtualPath">Accepts Virtual Path</param>
    /// <returns>string as inline css</returns>
    public static string InlineStyle(string VirtualPath)
    {
        var CSSBundle = BundleTable.Bundles.GetBundleFor(VirtualPath);
        var CSS = CSSBundle.GenerateBundleResponse(new BundleContext(new System.Web.HttpContextWrapper(System.Web.HttpContext.Current), BundleTable.Bundles, string.Empty)).Content;
        return string.Format("<style type='text/css'>{0}</style>",CSS);
    }
    /// <summary>
    /// Returns inline script with script tag
    /// </summary>
    /// <param name="VirtualPath">Accepts Virtual Path</param>
    /// <returns>string as inline script</returns>
    public static string InlineScript(string VirtualPath)
    {
        var JSBundle = BundleTable.Bundles.GetBundleFor(VirtualPath);
        var JS = JSBundle.GenerateBundleResponse(new BundleContext(new System.Web.HttpContextWrapper(System.Web.HttpContext.Current), BundleTable.Bundles, string.Empty)).Content;
        return string.Format("<script type='text/javascript'>{0}</script>", JS);
    }
}

并且在您的 ASP.NET 页面中,您可以按如下方式调用该方法

<%=BundleExtensions.InlineStyle("~/css/new_home_page") %>

谢谢你:)