-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Using GZip to compress swagger-ui-dist files in embedded resource to reduce the output dll size #3399
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
martincostello
merged 17 commits into
domaindrivendev:master
from
stratosblue:reduce_ui_dll_size
Jul 7, 2025
Merged
Using GZip to compress swagger-ui-dist files in embedded resource to reduce the output dll size #3399
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
60e3d8e
Using GZip to compress swagger-ui-dist files in embedded resource to …
stratosblue c73a5a1
Using GZip to compress redoc/bundles files.
stratosblue 9eb1cb1
Static assets now response with gzip directly if client supported
stratosblue 24cef15
Chore for embedded resource compression
stratosblue fc3d646
Merge branch 'master' into reduce_ui_dll_size
stratosblue e22a8ee
Remove netstandard support
stratosblue 3f5e9e2
Embed compressed file using sdk task
stratosblue 7cf2bf8
Fix SwaggerUIMiddleware test
stratosblue e5a585a
Update test/Swashbuckle.AspNetCore.IntegrationTests/Swashbuckle.AspNe…
stratosblue 3734eb5
Update test/Swashbuckle.AspNetCore.IntegrationTests/SwaggerUIIntegrat…
stratosblue 1b4e199
Update test/Swashbuckle.AspNetCore.IntegrationTests/SwaggerUIIntegrat…
stratosblue c00bd4c
Update test/Swashbuckle.AspNetCore.IntegrationTests/SwaggerUIIntegrat…
stratosblue db3881e
Update src/Shared/HttpContextAcceptEncodingCheckExtensions.cs
stratosblue 5a91b1d
Update src/Shared/HttpContextAcceptEncodingCheckExtensions.cs
stratosblue eb2550e
Update src/Shared/HttpContextAcceptEncodingCheckExtensions.cs
stratosblue 887d9f0
Chore for PR
stratosblue c951c4e
remove unnecessary gitignore
stratosblue File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| .dotnet/ | ||
| .dotnet/ | ||
| .DS_Store | ||
| .vs/ | ||
| .idea* | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| #nullable enable | ||
|
|
||
| using System.Collections.Frozen; | ||
| using System.IO.Compression; | ||
| using System.Reflection; | ||
| using System.Security.Cryptography; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.StaticFiles; | ||
| using Microsoft.Extensions.Primitives; | ||
| using Microsoft.Net.Http.Headers; | ||
|
|
||
| namespace Swashbuckle.AspNetCore; | ||
|
|
||
| internal class CompressedEmbeddedFileResponder | ||
| { | ||
| private readonly Assembly _assembly; | ||
|
|
||
| private readonly StringValues _cacheControlHeaderValue; | ||
|
|
||
| private readonly FileExtensionContentTypeProvider _contentTypeProvider = new(); | ||
|
|
||
| private readonly string _pathPrefix; | ||
|
|
||
| private readonly FrozenDictionary<string, ResourceIndexCache> _resourceMap; | ||
|
|
||
| public CompressedEmbeddedFileResponder(Assembly assembly, string resourceNamePrefix, string pathPrefix, TimeSpan? cacheLifetime) | ||
| { | ||
| _assembly = assembly ?? throw new ArgumentNullException(nameof(assembly)); | ||
| _pathPrefix = pathPrefix.TrimEnd('/'); | ||
| _cacheControlHeaderValue = GetCacheControlHeaderValue(cacheLifetime); | ||
|
|
||
| var resourceMap = assembly.GetManifestResourceNames() | ||
| .Where(name => name.StartsWith(resourceNamePrefix, StringComparison.Ordinal)) | ||
| .ToDictionary(name => name.Substring(resourceNamePrefix.Length), name => new ResourceIndexCache(name), StringComparer.Ordinal); | ||
|
|
||
| _resourceMap = resourceMap.ToFrozenDictionary(); | ||
| } | ||
|
|
||
| public async Task<bool> TryRespondWithFileAsync(HttpContext httpContext) | ||
| { | ||
| var path = httpContext.Request.Path.Value?.ToString() ?? string.Empty; | ||
| if (!path.StartsWith(_pathPrefix, StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| path = path.Substring(_pathPrefix.Length).Replace('/', '.'); | ||
|
|
||
| if (!_resourceMap.TryGetValue(path, out var resourceIndexCache)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| var contentType = GetContentType(resourceIndexCache); | ||
| var (etag, Length) = GetDecompressContentETag(resourceIndexCache); | ||
|
|
||
| var responseHeaders = httpContext.Response.Headers; | ||
| var ifNoneMatch = httpContext.Request.Headers.IfNoneMatch.ToString(); | ||
| if (ifNoneMatch == etag) | ||
| { | ||
| httpContext.Response.StatusCode = StatusCodes.Status304NotModified; | ||
| return true; | ||
| } | ||
|
|
||
| var responseWithGZip = httpContext.IsGZipAccepted(); | ||
| if (responseWithGZip) | ||
| { | ||
| responseHeaders.ContentEncoding = "gzip"; | ||
| } | ||
|
|
||
| responseHeaders.ContentType = contentType; | ||
| responseHeaders.ETag = etag; | ||
| responseHeaders.CacheControl = _cacheControlHeaderValue; | ||
|
|
||
| using var stream = OpenResourceStream(resourceIndexCache); | ||
| if (responseWithGZip) | ||
| { | ||
| responseHeaders.ContentLength = stream.Length; | ||
| await stream.CopyToAsync(httpContext.Response.Body, httpContext.RequestAborted); | ||
| } | ||
| else | ||
| { | ||
| responseHeaders.ContentLength = Length; | ||
| using var gzipStream = new GZipStream(stream, CompressionMode.Decompress); | ||
| await gzipStream.CopyToAsync(httpContext.Response.Body, httpContext.RequestAborted); | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| private static string GetCacheControlHeaderValue(TimeSpan? cacheLifetime) | ||
| { | ||
| if (cacheLifetime is { } maxAge) | ||
| { | ||
| return new CacheControlHeaderValue() | ||
| { | ||
| MaxAge = maxAge, | ||
| Private = true, | ||
| }.ToString(); | ||
| } | ||
| else | ||
| { | ||
| return new CacheControlHeaderValue() | ||
| { | ||
| NoCache = true, | ||
| NoStore = true, | ||
| }.ToString(); | ||
| } | ||
| } | ||
|
|
||
| private string GetContentType(ResourceIndexCache resourceIndexCache) | ||
| { | ||
| return resourceIndexCache.ContentType | ||
| ?? (_contentTypeProvider.TryGetContentType(resourceIndexCache.ResourceName, out var contentTypeValue) | ||
| ? contentTypeValue | ||
| : "application/octet-stream"); | ||
| } | ||
|
|
||
| private (string ETag, long DecompressContentLength) GetDecompressContentETag(ResourceIndexCache resourceIndexCache) | ||
| { | ||
| if (resourceIndexCache.ETag != null | ||
| && resourceIndexCache.DecompressContentLength != null) | ||
| { | ||
| return (resourceIndexCache.ETag, resourceIndexCache.DecompressContentLength.Value); | ||
| } | ||
|
|
||
| using var stream = OpenResourceStream(resourceIndexCache); | ||
|
|
||
| using var memoryStream = new MemoryStream((int)stream.Length * 2); | ||
| using var gzipStream = new GZipStream(stream, CompressionMode.Decompress); | ||
| gzipStream.CopyTo(memoryStream); | ||
| memoryStream.Seek(0, SeekOrigin.Begin); | ||
|
|
||
| resourceIndexCache.DecompressContentLength = memoryStream.Length; | ||
|
|
||
| var hashData = SHA1.HashData(memoryStream); | ||
|
|
||
| resourceIndexCache.ETag = $"\"{Convert.ToBase64String(hashData)}\""; | ||
|
|
||
| return (resourceIndexCache.ETag, resourceIndexCache.DecompressContentLength.Value); | ||
| } | ||
|
|
||
| private Stream OpenResourceStream(ResourceIndexCache resourceIndexCache) | ||
| { | ||
| // Actually, since the name comes from GetManifestResourceNames(), the content can definitely be obtained | ||
| return _assembly.GetManifestResourceStream(resourceIndexCache.ResourceName)!; | ||
| } | ||
|
|
||
| private sealed class ResourceIndexCache(string resourceName) | ||
| { | ||
| public string? ContentType { get; set; } | ||
|
|
||
| public long? DecompressContentLength { get; set; } | ||
|
|
||
| public string? ETag { get; set; } | ||
|
|
||
| public string ResourceName { get; } = resourceName; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| #nullable enable | ||
|
|
||
| using Microsoft.AspNetCore.Http; | ||
|
|
||
| namespace Swashbuckle.AspNetCore; | ||
|
|
||
| internal static class HttpContextAcceptEncodingCheckExtensions | ||
| { | ||
| public static bool IsGZipAccepted(this HttpContext httpContext) | ||
| { | ||
| var acceptEncoding = httpContext.Request.Headers.AcceptEncoding; | ||
|
|
||
| for (var index = 0; index < acceptEncoding.Count; index++) | ||
| { | ||
| var stringValue = acceptEncoding[index].AsSpan(); | ||
| if (stringValue.Contains("gzip", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.