Skip to content
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

Move inline css and js to external files for SwaggerUI and ReDoc #2965

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 43 additions & 20 deletions src/Swashbuckle.AspNetCore.ReDoc/ReDocMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,24 +53,30 @@ public ReDocMiddleware(
public async Task Invoke(HttpContext httpContext)
{
var httpMethod = httpContext.Request.Method;
var path = httpContext.Request.Path.Value;

// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (httpMethod == "GET" && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
if (HttpMethods.IsGet(httpMethod))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";
var path = httpContext.Request.Path.Value;

RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}
// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";

if (httpMethod == "GET" && Regex.IsMatch(path, $"/{_options.RoutePrefix}/?index.html", RegexOptions.IgnoreCase))
{
await RespondWithIndexHtml(httpContext.Response);
return;
RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}

var match = Regex.Match(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?(index.(html|css|js))$", RegexOptions.IgnoreCase);

if (match.Success)
{
await RespondWithFile(httpContext.Response, match.Groups[1].Value);
return;
}
}

await _staticFileMiddleware.Invoke(httpContext);
Expand All @@ -97,21 +103,38 @@ private void RespondWithRedirect(HttpResponse response, string location)
response.Headers["Location"] = location;
}

private async Task RespondWithIndexHtml(HttpResponse response)
private async Task RespondWithFile(HttpResponse response, string fileName)
{
response.StatusCode = 200;
response.ContentType = "text/html";

using (var stream = _options.IndexStream())
Stream stream;

switch (fileName)
{
case "index.css":
response.ContentType = "text/css";
stream = ResourceHelper.GetEmbeddedResource(fileName);
break;
case "index.js":
response.ContentType = "application/javascript;charset=utf-8";
stream = ResourceHelper.GetEmbeddedResource(fileName);
break;
default:
response.ContentType = "text/html;charset=utf-8";
stream = _options.IndexStream();
break;
}

using (stream)
{
// Inject arguments before writing to response
var htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd());
var content = new StringBuilder(new StreamReader(stream).ReadToEnd());
foreach (var entry in GetIndexArguments())
{
htmlBuilder.Replace(entry.Key, entry.Value);
content.Replace(entry.Key, entry.Value);
}

await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
await response.WriteAsync(content.ToString(), Encoding.UTF8);
}
}

Expand Down
6 changes: 2 additions & 4 deletions src/Swashbuckle.AspNetCore.ReDoc/ReDocOptions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.Json.Serialization;

namespace Swashbuckle.AspNetCore.ReDoc
Expand All @@ -16,8 +15,7 @@ public class ReDocOptions
/// <summary>
/// Gets or sets a Stream function for retrieving the redoc page
/// </summary>
public Func<Stream> IndexStream { get; set; } = () => typeof(ReDocOptions).GetTypeInfo().Assembly
.GetManifestResourceStream("Swashbuckle.AspNetCore.ReDoc.index.html");
public Func<Stream> IndexStream { get; set; } = () => ResourceHelper.GetEmbeddedResource("index.html");

/// <summary>
/// Gets or sets a title for the redoc page
Expand Down Expand Up @@ -111,4 +109,4 @@ public class ConfigObject
[JsonExtensionData]
public Dictionary<string, object> AdditionalItems { get; set; } = new Dictionary<string, object>();
}
}
}
13 changes: 13 additions & 0 deletions src/Swashbuckle.AspNetCore.ReDoc/ResourceHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.IO;
using System.Reflection;

namespace Swashbuckle.AspNetCore.ReDoc;

internal static class ResourceHelper
{
public static Stream GetEmbeddedResource(string fileName)
{
return typeof(ResourceHelper).GetTypeInfo().Assembly
.GetManifestResourceStream($"Swashbuckle.AspNetCore.ReDoc.{fileName}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@
</PropertyGroup>

<ItemGroup>
<None Remove="index.css" />
<None Remove="index.js" />
</ItemGroup>

<ItemGroup>
<EmbeddedResource Include="index.css" />
<EmbeddedResource Include="index.html" />
<EmbeddedResource Include="index.js" />
<EmbeddedResource Include="node_modules/redoc/bundles/redoc.standalone.js" />
</ItemGroup>

Expand Down
4 changes: 4 additions & 0 deletions src/Swashbuckle.AspNetCore.ReDoc/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
body {
margin: 0;
padding: 0;
}
13 changes: 3 additions & 10 deletions src/Swashbuckle.AspNetCore.ReDoc/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,12 @@
<!--
Redoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
<link href="index.css" rel="stylesheet" type="text/css">
%(HeadContent)
</head>
<body>
<div id="redoc-container"></div>
<script src="redoc.standalone.js"></script>
<script type="text/javascript">
Redoc.init('%(SpecUrl)', JSON.parse('%(ConfigObject)'), document.getElementById('redoc-container'))
</script>
<script src="index.js"></script>
</body>
</html>
</html>
1 change: 1 addition & 0 deletions src/Swashbuckle.AspNetCore.ReDoc/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Redoc.init('%(SpecUrl)', JSON.parse('%(ConfigObject)'), document.getElementById('redoc-container'));
martincostello marked this conversation as resolved.
Show resolved Hide resolved
13 changes: 13 additions & 0 deletions src/Swashbuckle.AspNetCore.SwaggerUI/ResourceHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.IO;
using System.Reflection;

namespace Swashbuckle.AspNetCore.SwaggerUI;

internal static class ResourceHelper
{
public static Stream GetEmbeddedResource(string fileName)
{
return typeof(ResourceHelper).GetTypeInfo().Assembly
.GetManifestResourceStream($"Swashbuckle.AspNetCore.SwaggerUI.{fileName}");
}
}
60 changes: 38 additions & 22 deletions src/Swashbuckle.AspNetCore.SwaggerUI/SwaggerUIMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,26 +64,30 @@ public SwaggerUIMiddleware(
public async Task Invoke(HttpContext httpContext)
{
var httpMethod = httpContext.Request.Method;
var path = httpContext.Request.Path.Value;

var isGet = HttpMethods.IsGet(httpMethod);

// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (isGet && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
if (HttpMethods.IsGet(httpMethod))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";
var path = httpContext.Request.Path.Value;

RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}
// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";

if (isGet && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?index.html$", RegexOptions.IgnoreCase))
{
await RespondWithIndexHtml(httpContext.Response);
return;
RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}

var match = Regex.Match(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?(index.(html|js))$", RegexOptions.IgnoreCase);

if (match.Success)
{
await RespondWithFile(httpContext.Response, match.Groups[1].Value);
return;
}
}

await _staticFileMiddleware.Invoke(httpContext);
Expand All @@ -110,23 +114,35 @@ private static void RespondWithRedirect(HttpResponse response, string location)
response.Headers["Location"] = location;
}

private async Task RespondWithIndexHtml(HttpResponse response)
private async Task RespondWithFile(HttpResponse response, string fileName)
{
response.StatusCode = 200;
response.ContentType = "text/html;charset=utf-8";

using (var stream = _options.IndexStream())
Stream stream;

if (fileName == "index.js")
{
response.ContentType = "application/javascript;charset=utf-8";
stream = ResourceHelper.GetEmbeddedResource(fileName);
}
else
{
response.ContentType = "text/html;charset=utf-8";
stream = _options.IndexStream();
}

using (stream)
{
using var reader = new StreamReader(stream);

// Inject arguments before writing to response
var htmlBuilder = new StringBuilder(await reader.ReadToEndAsync());
var content = new StringBuilder(await reader.ReadToEndAsync());
foreach (var entry in GetIndexArguments())
{
htmlBuilder.Replace(entry.Key, entry.Value);
content.Replace(entry.Key, entry.Value);
}

await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
await response.WriteAsync(content.ToString(), Encoding.UTF8);
}
}

Expand Down
6 changes: 2 additions & 4 deletions src/Swashbuckle.AspNetCore.SwaggerUI/SwaggerUIOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;

Expand All @@ -18,8 +17,7 @@ public class SwaggerUIOptions
/// <summary>
/// Gets or sets a Stream function for retrieving the swagger-ui page
/// </summary>
public Func<Stream> IndexStream { get; set; } = () => typeof(SwaggerUIOptions).GetTypeInfo().Assembly
.GetManifestResourceStream("Swashbuckle.AspNetCore.SwaggerUI.index.html");
public Func<Stream> IndexStream { get; set; } = () => ResourceHelper.GetEmbeddedResource("index.html");

/// <summary>
/// Gets or sets a title for the swagger-ui page
Expand All @@ -34,7 +32,7 @@ public class SwaggerUIOptions
/// <summary>
/// Gets the JavaScript config object, represented as JSON, that will be passed to the SwaggerUI
/// </summary>
public ConfigObject ConfigObject { get; set; } = new ConfigObject();
public ConfigObject ConfigObject { get; set; } = new ConfigObject();

/// <summary>
/// Gets the JavaScript config object, represented as JSON, that will be passed to the initOAuth method
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

<ItemGroup>
<EmbeddedResource Include="node_modules/swagger-ui-dist/**/*" Exclude="**/*/index.html;**/*/*.map;**/*/*.json;**/*/*.md;**/*/swagger-ui-es-*" />
<EmbeddedResource Include="index.html" />
<None Remove="index.html;index.js" />
<EmbeddedResource Include="index.html;index.js" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
Expand Down
Loading