-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHtmlMinifierMiddleware.cs
55 lines (41 loc) · 1.59 KB
/
HtmlMinifierMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using HtmlAgilityPack;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arex388.AspNetCore {
public sealed class HtmlMinifierMiddleware {
private static readonly string[] ContentTypes = {
"text/html; charset=utf-8",
"text/xml"
};
private readonly RequestDelegate _next;
public HtmlMinifierMiddleware(
RequestDelegate next) => _next = next ?? throw new ArgumentNullException(nameof(next));
public async Task InvokeAsync(
HttpContext context) {
var response = context.Response;
var stream = response.Body;
try {
await using var memoryStream = new MemoryStream();
response.Body = memoryStream;
await _next(context).ConfigureAwait(false);
memoryStream.Seek(0, SeekOrigin.Begin);
if (!ContentTypes.Contains(response.ContentType)) {
await memoryStream.CopyToAsync(stream).ConfigureAwait(false);
return;
}
var document = new HtmlDocument();
document.Load(memoryStream, Encoding.UTF8);
document.DocumentNode.TrimWhitespace();
var html = document.DocumentNode.OuterHtml;
var htmlBytes = Encoding.UTF8.GetBytes(html);
await stream.WriteAsync(htmlBytes).ConfigureAwait(false);
} finally {
response.Body = stream;
}
}
}
}