简体   繁体   English

ASP.NET MVC C#Razor Minification

[英]ASP.NET MVC C# Razor Minification

Does anybody have any idea about how to output minified HTML and JavaScript from the Razor engine while keeping custom coding styles? 有没有人知道如何在保持自定义编码样式的同时从Razor引擎输出缩小的HTML和JavaScript?

For example: i want the following code: 例如:我想要以下代码:

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

To be outputted as <div id="DivId"></div> . 输出为<div id="DivId"></div>

Look at http://arranmaclean.wordpress.com/2010/08/10/minify-html-with-net-mvc-actionfilter/ . 请查看http://arranmaclean.wordpress.com/2010/08/10/minify-html-with-net-mvc-actionfilter/ there is an example for creating custom action filter witch clear html from WhiteSpaces 有一个例子可以从WhiteSpaces创建自定义动作过滤器清除html

Update : The source code quoted from above. 更新 :上面引用的源代码。

The stream class for removing "blanks" 用于删除“空白”的流类

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));
        }
    }
}

The ActionFilter class: 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;
                });

        }

}

And in the end the usage of above: 并最终使用上述:

[HandleError]
[WhitespaceFilter]
public class HomeController : Controller
{
     ...
}

I don't think that there is any way to achieve that. 我认为没有办法实现这一目标。 To avoid the tag soup I usually prefer writing custom helpers: 为了避免标签汤,我通常更喜欢写自定义助手:

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

and here's how the custom helper might look like: 以下是自定义帮助程序的外观:

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);            
    }
}

Alternatively you could also do a tag soup: 或者你也可以做一个标签汤:

<div@Html.Raw(Model.Name != string.Empty ? string.Format(" id=\"{0}\"", Html.AttributeEncode(Model.Name)) : string.Empty)>
</div>

Maybe you looking for Meleze.Web 也许您正在寻找Meleze.Web

Meleze.Web is a toolbox to optimize ASP.NET MVC 3.0 and MVC 4.0 applications. Meleze.Web是一个优化ASP.NET MVC 3.0和MVC 4.0应用程序的工具箱。
It provides HTML, JS and CSS minification of Razor views and caching of the returned pages. 它提供了Razor视图的HTML,JS和CSS缩小以及返回页面的缓存。

Darin Dimitrov write about it here: ASP.Net MVC Razor Views - Minifying HTML at build time Darin Dimitrov在这里写到: ASP.Net MVC Razor Views - 在构建时缩小HTML

But I think enabling gzip is better solution, you could read about it here: Minify HTML output from an ASP.Net MVC Application 但我认为启用gzip是更好的解决方案,你可以在这里阅读: 从ASP.Net MVC应用程序中简化HTML输出

For anybody interested in this, I built a simple HTML minification library that can be used with MVC 5: 对于任何对此感兴趣的人,我构建了一个可以与MVC 5一起使用的简单HTML缩小库:

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

It operates in compile-time instead of runtime, so it doesn't add any performance overhead. 它在编译时而不是运行时运行,因此不会增加任何性能开销。 The minification is very simple (just replaces lots of spaces with one space). 缩小非常简单(只需用一个空格替换大量空格)。

Even with GZIP enabled on top of the minified HTML, it can still reduce the payload size . 即使在缩小的HTML之上启用了GZIP,它仍然可以减少有效负载大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM