11

有没有人知道如何从 Razor 引擎输出缩小的 HTML 和 JavaScript,同时保持自定义编码样式?

例如:我想要以下代码:

<div
    @if (Model.Name != string.Empty)
        @:id="@Model.Name"
>
</div>

输出为<div id="DivId"></div>.

4

4 回答 4

13

查看http://arranmaclean.wordpress.com/2010/08/10/minify-html-with-net-mvc-actionfilter/。有一个从 WhiteSpaces 创建自定义操作过滤器清除 html 的示例

更新:上面引用的源代码。

用于删除“空白”的流类

using System;
using System.IO;
using System.Text;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace RemoveWhiteSpace.ActionFilters
{
    public class WhiteSpaceFilter : Stream
    {

        private Stream _shrink;
        private Func<string, string> _filter;

        public WhiteSpaceFilter(Stream shrink, Func<string, string> filter)
        {
            _shrink = shrink;
            _filter = filter;
        }


        public override bool CanRead { get { return true; } }
        public override bool CanSeek { get { return true; } }
        public override bool CanWrite { get { return true; } }
        public override void Flush() { _shrink.Flush(); }
        public override long Length { get { return 0; } }
        public override long Position { get; set; }
        public override int Read(byte[] buffer, int offset, int count)
        {
            return _shrink.Read(buffer, offset, count);
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            return _shrink.Seek(offset, origin);
        }
        public override void SetLength(long value)
        {
            _shrink.SetLength(value);
        }
        public override void Close()
        {
            _shrink.Close();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            // capture the data and convert to string 
            byte[] data = new byte[count];
            Buffer.BlockCopy(buffer, offset, data, 0, count);
            string s = Encoding.Default.GetString(buffer);

            // filter the string
            s = _filter(s);

            // write the data to stream 
            byte[] outdata = Encoding.Default.GetBytes(s);
            _shrink.Write(outdata, 0, outdata.GetLength(0));
        }
    }
}

ActionFilter班级:

public class WhitespaceFilterAttribute : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        var request = filterContext.HttpContext.Request;
        var response = filterContext.HttpContext.Response;

        response.Filter = new WhiteSpaceFilter(response.Filter, s =>
                {
                    s = Regex.Replace(s, @"\s+", " ");
                    s = Regex.Replace(s, @"\s*\n\s*", "\n");
                    s = Regex.Replace(s, @"\s*\>\s*\<\s*", "><");
                    s = Regex.Replace(s, @"<!--(.*?)-->", "");   //Remove comments

                    // single-line doctype must be preserved 
                    var firstEndBracketPosition = s.IndexOf(">");
                    if (firstEndBracketPosition >= 0)
                    {
                        s = s.Remove(firstEndBracketPosition, 1);
                        s = s.Insert(firstEndBracketPosition, ">");
                    }
                    return s;
                });

        }

}

最后使用上面的用法:

[HandleError]
[WhitespaceFilter]
public class HomeController : Controller
{
     ...
}
于 2013-04-08T11:49:26.547 回答
4

我认为没有任何方法可以实现这一目标。为了避免标签汤,我通常更喜欢编写自定义助手:

@using(Html.MyDiv(Model.Name))
{
    ... put the contents of the div here
}

下面是自定义助手的样子:

public static class HtmlExtensions
{
    private class Div : IDisposable
    {
        private readonly ViewContext context;
        private bool disposed;

        public Div(ViewContext context)
        {
            this.context = context;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                this.disposed = true;
                context.Writer.Write("</div>");
            }
        }
    }

    public static IDisposable MyDiv(this HtmlHelper html, string id)
    {
        var div = new TagBuilder("div");
        if (!string.IsNullOrEmpty(id))
        {
            div.GenerateId(id);
        }
        html.ViewContext.Writer.Write(div.ToString(TagRenderMode.StartTag));
        return new Div(html.ViewContext);            
    }
}

或者你也可以做一个标签汤:

<div@Html.Raw(Model.Name != string.Empty ? string.Format(" id=\"{0}\"", Html.AttributeEncode(Model.Name)) : string.Empty)>
</div>
于 2013-04-08T11:31:35.707 回答
3

也许您正在寻找Meleze.Web

Meleze.Web 是一个优化 ASP.NET MVC 3.0 和 MVC 4.0 应用程序的工具箱。
它提供了 Razor 视图的 HTML、JS 和 CSS 缩小以及返回页面的缓存。

Darin Dimitrov在这里写下它:ASP.Net MVC Razor Views - Minifying HTML at build time

但我认为启用gzip是更好的解决方案,你可以在这里阅读:Minify HTML output from an ASP.Net MVC Application

于 2013-04-08T11:42:12.547 回答
1

对于任何对此感兴趣的人,我构建了一个可以与 MVC 5 一起使用的简单 HTML 缩小库:

https://github.com/tompazourek/RazorHtmlMinifier.Mvc5

它在编译时而不是运行时运行,因此不会增加任何性能开销。缩小非常简单(只需用一个空格替换很多空格)。

即使在缩小的 HTML 之上启用了 GZIP,它仍然可以减小有效负载大小

于 2017-11-20T22:41:49.033 回答