Is there a way to minimize HTML in ASP.NET MVC Razor?

Asked 2 years ago, Updated 2 years ago, 109 views

The VS2013.NET Framework 4.5 Environment View Engine utilizes "Razor".

Is there a simple way to generate HTML with minimal space and line breaks, such as {trip} tags in PHP Smarty?

I look forward to your kind cooperation.

.net asp.net razor

2022-09-30 20:27

4 Answers

Visual Studio EnhancementsSideWaffle provides an HTTP module called WhitespaceModule for Minify.

https://github.com/ligershark/side-waffle/blob/master/TemplatePack/ItemTemplates/Web/ASP.NET/WhitespaceModule/WhitespaceModule.cs

The main implementation is the WhitespaceFilter class, so you can also use ActionFilter to set it to Response.Filter.

http://forums.asp.net/t/1380989.aspx

However, in many cases, multi-byte characters are not considered, so you should be careful about that.


2022-09-30 20:27

It seems that requests sometimes go up, but officially not yet.

aspnet/Mvcissues

It says close, but it's not that it doesn't respond, it's that we're discussing it as a new feature instead of a challenge.

I have never used it either, but it seems that there are several other things besides WebMarkupMin.Mvc that have already been uploaded.

WebMarkupMin.Mvc seems to use action filter to process HTML or XHTML.The behavior of the items listed below seems to be slightly different.

https://github.com/Chebur9tina/HtmlOptimizerMvc4
It seems that this will minimize the laser view when building, not when running. It's for MVC4 (I saw what someone else made for MVC5 on bitbucket)

http://nuget.org/List/Packages/Meleze.Web (https://github.com/meleze/Meleze.Web)
This one seems to minimize the radio.However, I have seen that the partial view is not minimized or that only the body is minimized, so the whole thing may not be minimized.


2022-09-30 20:27

Razor is not suitable for processing only for a specific range of HTML written inline.
If you want to force a partial mini like {trip},

public static MvcHtmlString StripWhitespaces (this HtmlHelper self, Func<object, HelperResult>template)
{
    // This is the simplest example of miniify.
    return new MvcHtmlString(template(self.ViewData.Model).ToString()
        .Replace("\r", "").Replace("\n", "").Replace("", "").Replace("\t", "");
}

With this kind of extension method in place, you can use it as follows:

@Html.StripWhitespace(@<text>
    <h1>
        hogehoge
    </h1>
</text>)

If you want to minimize the entire output, I think you can only use HttpModule or ActionFilter as you said.


2022-09-30 20:27

I have never used it, but I am interested in it, so I looked it up.
Wouldn't WebMarkupMin.Mvc be good?


2022-09-30 20:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.