【问题标题】:ASP.NET CssMinify, HttpContextBaseASP.NET CssMinify、HttpContextBase
【发布时间】:2014-02-11 16:34:46
【问题描述】:

我有一个 ASP.NET 应用程序,它需要有多个视图布局。有一个普通的网页布局,以及一个没有依赖关系的独立页面的“静态”布局(用作文档管理系统中的显示模板)。

让视图切换其布局很容易。

因此,一体式页面布局需要将其所有 CSS 包含在页面内的 <style> 标记中。我找到了一种方法来找出捆绑包中的文件并编写了如下方法:

@MyCode.IncludeCSS("~/StaticLayout/css")

它读取包中的 CSS 文件并将其内容发送到页面中的 <style> 标记内。

但我想缩小 CSS。

我找不到System.Web.Optimization.CssMinify 的任何文档。您需要调用Process 方法,该方法需要BundleContext。所以...找到一个,创建一个? MSDN isn't much use:

public BundleContext(
    HttpContextBase context,
    BundleCollection collection,
    string bundleVirtualPath
)

Parameters
    context
        Type: System.Web.HttpContextBase
        The context.

嗯,这绝对有用。我无法知道context(类型为上下文)是上下文,直到雷德蒙德的某个脑胀的智力巨人从他忙碌的午睡中抽出一些时间,用他的小胖子把一篇明确的文章推到了它前面爪子在昏倒在一滩温暖的口水之前。

尽管如此,我仍然不知道它是什么,也不知道你从哪里得到它,Google 也不知道。 HttpContext.Current 不是从它派生的,也没有属性(我能找到)。

This page 有一些关于正常捆绑的好信息,但它假定框架将以传统方式进行捆绑并提供捆绑内容,作为单独请求的资源。

有人做过吗?

【问题讨论】:

  • 快速提示:您可以毫无困难地获得HttpContextBase 的实例:new HttpContextWrapper( HttpContext.Current )(或使用您选择的 DI 框架注入以避免硬编码依赖项)。

标签: asp.net css asp.net-mvc asp.net-mvc-4 minify


【解决方案1】:

埃德·普朗克特,

如果您将其用作 HTML 帮助程序,则可以从 ViewContext.HttpContext 属性中获取 HttpContextBase。可以这样创建。

public static IHtmlString BundleCss(this HtmlHelper html, string outputPath, params string[] cssFilePaths)
{
    var collection = new BundleCollection();
    foreach (var cssFilePath in cssFilePaths)
        collection.Add(new Bundle(cssFilePath));

    var bundler = new BundleContext(html.ViewContext.HttpContext, collection, outputPath);
    //... ommitted code
    System.Web.Optimization.CssMinify minify = new CssMinify();
    minify.Process(bundler, response);
    //... TODO: Grab the response content and return
}

是的,这是一个使用 HTML 助手的基本示例。如果这不能回答您的问题,请告诉我。

编辑:重新阅读问题后,我正在澄清我的回答。因此,以上内容有助于从问题中找到 HttpContextBase 属性。但是我认为问题是您如何实际读取文件的内容,将它们缩小并将它们放入页面上的<style> 标记中。

我尝试编写自己对您的要求的解释,并提出了以下一组类

我的 CssOutputBundler 类:

public class CssOutputBundler
{
    static readonly Dictionary<string, string> cachedOutput = new Dictionary<string, string>();
    readonly string tempFileOutputPath;
    readonly HtmlHelper helper;
    readonly IList<string> virtualFilePaths;

    public CssOutputBundler(HtmlHelper helper, string tempFileOutputPath)
    {
        if (helper == null)
            throw new ArgumentNullException("helper null");
        if (string.IsNullOrWhiteSpace(tempFileOutputPath))
            this.tempFileOutputPath = tempFileOutputPath;
        this.helper = helper;
        this.virtualFilePaths = new List<string>();
        this.tempFileOutputPath = tempFileOutputPath;
    }

    public CssOutputBundler Add(string cssFilePath)
    {
        if (!this.virtualFilePaths.Contains(cssFilePath))
            this.virtualFilePaths.Add(cssFilePath);
        return this;
    }

    public IHtmlString Minify()
    {
        if (helper == null)
            throw new ArgumentNullException("helper null");

        string cache_string = string.Join(",", this.virtualFilePaths);
        if(cachedOutput.ContainsKey(cache_string))
            return formatResponse(File.ReadAllText(cachedOutput[cache_string]));
        var bundle = new StyleBundle(this.tempFileOutputPath).Include(this.virtualFilePaths.ToArray());
        var collection = new BundleCollection();
        collection.Add(bundle);
        var context = new BundleContext(helper.ViewContext.HttpContext, collection, "");
        var response = bundle.GenerateBundleResponse(context);
        System.Web.Optimization.CssMinify minify = new CssMinify();
        minify.Process(context, response);
        string serverPath = helper.ViewContext.HttpContext.Server.MapPath(this.tempFileOutputPath);
        string outputPath = Guid.NewGuid().ToString() + ".css";
        while(File.Exists(Path.Combine(serverPath, outputPath)))
            outputPath = Guid.NewGuid().ToString() + ".css";

        File.WriteAllText(outputPath, response.Content);
        cachedOutput[cache_string] = outputPath;
        return formatResponse(response.Content);
    }

    IHtmlString formatResponse(string responseContent)
    {
        StringBuilder responseBuilder = new StringBuilder();
        responseBuilder.AppendLine("<style type=\"text/css\">");
        responseBuilder.Append(responseContent);
        responseBuilder.AppendLine("</style>");
        return helper.Raw(responseBuilder.ToString());
    }
}

好的,上面的类看起来很复杂,但它所做的只是为捆绑器创建一个内部路径列表,以便捆绑和缩小。当调用 Minify 方法时,它会将虚拟路径格式化为用作 缓存键 的字符串。这就是我们确定是否已经捆绑和缩小这些脚本的方式。

如果我们从存储在 HDD 上的临时捆绑脚本中读取。

注意: 我使用的是硬盘存储而不是内存存储。这可以通过将全部内容填充到静态字典或其他缓存介质中轻松更改。

如果此文件集尚未捆绑、缩小等,那么我们将继续捆绑并缩小该集。最后,我们将文件存储到 HDD 上并返回响应。所以这很容易。

现在要实现这个类,我刚刚写了一个快速的 HTML Helper,因为 Minification 类支持 Add 文件的链接方法可以很好地实现。

HTML 助手:

public static CssOutputBundler BundleCss(this HtmlHelper helper, string outputVirtualPath)
{
    return new CssOutputBundler(helper, outputVirtualPath);
}

打包器的基本实现。现在这个助手接受字符串outputVirtualPath 这是存储临时文件的虚拟路径。如果您决定不保存到 HDD 并使用缓存系统,您可以从帮助程序和类中删除此参数。

最后,这可以在您的视图中用作...

@Html.BundleCss("~/Content/").Add("~/Content/Site.css").Add("~/Content/themes/base/jquery-ui.css").Minify();

~/Content/ 是 HDD 上用于存储缩小文件的虚拟路径。然后我们添加两个文件"~/Content/Site.css" 和~/Content/themes/base/jquery-ui.css。最后调用返回 html 字符串的 minify 方法。比如……

<style type="text/css">
.ui-helper-hidden{display:none}.ui-helper-hidden-accessible{position:absolute!important;clip:rect(1px 1px 1px 1px);clip:rect(1px,1px,1px,1px)} ....more css
</style>

干杯。

【讨论】:

  • 这是一个开始,谢谢。 outputPath 是什么?你知道[BundleResponse](http://msdn.microsoft.com/en-us/library/dn202155(v=vs.110).aspx)吗?
  • 哇。这些天,他们真的有顶尖人物设计 API。非常感谢您的帮助!
  • 很高兴你把它整理好了。干杯。
猜你喜欢
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 2011-07-04
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多