-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
ResponseCompressionMiddleware.cs
73 lines (63 loc) · 2.32 KB
/
ResponseCompressionMiddleware.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
namespace Microsoft.AspNetCore.ResponseCompression
{
/// <summary>
/// Enable HTTP response compression.
/// </summary>
public class ResponseCompressionMiddleware
{
private readonly RequestDelegate _next;
private readonly IResponseCompressionProvider _provider;
/// <summary>
/// Initialize the Response Compression middleware.
/// </summary>
/// <param name="next"></param>
/// <param name="provider"></param>
public ResponseCompressionMiddleware(RequestDelegate next, IResponseCompressionProvider provider)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
_next = next;
_provider = provider;
}
/// <summary>
/// Invoke the middleware.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
if (!_provider.CheckRequestAcceptsCompression(context))
{
await _next(context);
return;
}
var originalBodyFeature = context.Features.Get<IHttpResponseBodyFeature>();
var originalCompressionFeature = context.Features.Get<IHttpsCompressionFeature>();
var compressionBody = new ResponseCompressionBody(context, _provider, originalBodyFeature);
context.Features.Set<IHttpResponseBodyFeature>(compressionBody);
context.Features.Set<IHttpsCompressionFeature>(compressionBody);
try
{
await _next(context);
await compressionBody.FinishCompressionAsync();
}
finally
{
context.Features.Set(originalBodyFeature);
context.Features.Set(originalCompressionFeature);
}
}
}
}