Skip to content

Commit

Permalink
AspNetCore Middleware Refinements
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelstaib committed Oct 31, 2022
1 parent 164a47a commit 9158360
Show file tree
Hide file tree
Showing 9 changed files with 29 additions and 23 deletions.
2 changes: 2 additions & 0 deletions src/HotChocolate/AspNetCore/src/AspNetCore/ContentType.cs
Expand Up @@ -11,6 +11,7 @@ internal static class ContentType
public const string MultiPartMixed = $"{Types.MultiPart}/{SubTypes.Mixed};{_boundary}";
public const string GraphQLResponse = $"{Types.Application}/{SubTypes.GraphQLResponse};{_utf8}";
public const string EventStream = $"{Types.Text}/{SubTypes.EventStream};{_utf8}";
public const string Html = $"{Types.Text}/{SubTypes.Html}";

private static readonly char[] _jsonArray =
{
Expand Down Expand Up @@ -44,5 +45,6 @@ public static class SubTypes
public const string Json = "json";
public const string Mixed = "mixed";
public const string EventStream = "event-stream";
public const string Html = "html";
}
}
Expand Up @@ -88,7 +88,7 @@ public static class EndpointRouteBuilderExtensions
.UseMiddleware<ToolDefaultFileMiddleware>(fileProvider, path)
.UseMiddleware<ToolOptionsFileMiddleware>(path)
.UseMiddleware<ToolStaticFileMiddleware>(fileProvider, path)
.UseMiddleware<HttpGetMiddleware>(schemaNameOrDefault)
.UseMiddleware<HttpGetMiddleware>(schemaNameOrDefault, path)
.Use(_ => context =>
{
context.Response.StatusCode = 404;
Expand Down
Expand Up @@ -5,10 +5,13 @@ namespace HotChocolate.AspNetCore;

internal static class HttpRequestExtensions
{
private const string _slash = "/";
private static readonly PathString _slashPath = new("/");

internal static bool AcceptHeaderContainsHtml(this HttpRequest request)
{
return request.Headers.TryGetValue(HeaderNames.Accept, out var values) &&
values.Count > 0 && (values[0]?.Contains("text/html") ?? false);
values.Count > 0 && (values[0]?.Contains(ContentType.Html) ?? false);
}

internal static bool IsGetOrHeadMethod(this HttpRequest request)
Expand All @@ -18,7 +21,7 @@ internal static bool IsGetOrHeadMethod(this HttpRequest request)

internal static bool PathEndsInSlash(this HttpRequest request)
{
return request.Path.Value?.EndsWith("/", StringComparison.Ordinal) ?? false;
return request.Path.Value?.EndsWith(_slash, StringComparison.Ordinal) ?? false;
}

internal static bool TryMatchPath(
Expand All @@ -31,11 +34,15 @@ internal static bool PathEndsInSlash(this HttpRequest request)

if (forDirectory && !request.PathEndsInSlash())
{
path += new PathString("/");
path += _slashPath;
}

if (path.StartsWithSegments(matchUrl, out subPath))
{
if (subPath.Value?.Length is 1 && subPath.Equals(_slashPath))
{
subPath = default;
}
return true;
}

Expand Down
Expand Up @@ -13,25 +13,30 @@ public sealed class HttpGetMiddleware : MiddlewareBase
{
private readonly IHttpRequestParser _requestParser;
private readonly IServerDiagnosticEvents _diagnosticEvents;
private readonly PathString _matchUrl;

public HttpGetMiddleware(
HttpRequestDelegate next,
IRequestExecutorResolver executorResolver,
IHttpResponseFormatter responseFormatter,
IHttpRequestParser requestParser,
IServerDiagnosticEvents diagnosticEvents,
PathString matchUrl,
string schemaName)
: base(next, executorResolver, responseFormatter, schemaName)
{
_requestParser = requestParser ??
throw new ArgumentNullException(nameof(requestParser));
_diagnosticEvents = diagnosticEvents ??
throw new ArgumentNullException(nameof(diagnosticEvents));
_matchUrl = matchUrl;
}

public async Task InvokeAsync(HttpContext context)
{
if (HttpMethods.IsGet(context.Request.Method) &&
context.Request.TryMatchPath(_matchUrl, false, out var subPath) &&
!subPath.HasValue &&
(context.GetGraphQLServerOptions()?.EnableGetRequests ?? true))
{
if (!IsDefaultSchema)
Expand Down
@@ -1,6 +1,6 @@
namespace HotChocolate.AspNetCore;

internal class HttpMultipartRequest
internal sealed class HttpMultipartRequest
{
public HttpMultipartRequest(string operations, IDictionary<string, IFile> fileMap)
{
Expand Down
Expand Up @@ -11,7 +11,7 @@ namespace HotChocolate.AspNetCore;
/// If so the file name is appended to the path and execution continues.
/// Note we don't just serve the file because it may require interpretation.
/// </summary>
public class ToolDefaultFileMiddleware
public sealed class ToolDefaultFileMiddleware
{
private const string _defaultFile = "index.html";
private readonly IFileProvider _fileProvider;
Expand Down
Expand Up @@ -6,7 +6,7 @@ namespace HotChocolate.AspNetCore;
/// <summary>
/// This middleware handles the Banana Cake Pop configuration file request.
/// </summary>
public class ToolOptionsFileMiddleware
public sealed class ToolOptionsFileMiddleware
{
private const string _configFile = "/bcp-config.json";
private readonly HttpRequestDelegate _next;
Expand Down
Expand Up @@ -12,7 +12,7 @@ namespace HotChocolate.AspNetCore;
/// <summary>
/// Enables serving static files for a given request path
/// </summary>
public class ToolStaticFileMiddleware
public sealed class ToolStaticFileMiddleware
{
private readonly IContentTypeProvider _contentTypeProvider;
private readonly IFileProvider _fileProvider;
Expand Down Expand Up @@ -105,7 +105,7 @@ private Task TryServeStaticFile(HttpContext context, string contentType, PathStr
return false;
}

private async Task SendAsync(HttpContext context, StaticFileInfo fileInfo)
private static async Task SendAsync(HttpContext context, StaticFileInfo fileInfo)
{
SetCompressionMode(context);
context.Response.StatusCode = 200;
Expand All @@ -131,7 +131,7 @@ private async Task SendAsync(HttpContext context, StaticFileInfo fileInfo)
}
}

private void SetCompressionMode(HttpContext context)
private static void SetCompressionMode(HttpContext context)
{
if (context.Features.Get<IHttpsCompressionFeature>() is { } c)
{
Expand Down
Expand Up @@ -13,6 +13,11 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Opa.Native" Version="0.41.0" PrivateAssets="Compile" IncludeAssets="Compile;Runtime;Native" />
</ItemGroup>

<ItemGroup>
<None Include="Policies/*.rego" CopyToOutputDirectory="PreserveNewest" />
<None Update="$(MSBuildProjectDirectory)\__resources__\*.*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
Expand All @@ -21,17 +26,4 @@
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Opa.Native" Version="0.41.0" PrivateAssets="Compile" IncludeAssets="Compile;Runtime;Native" />
</ItemGroup>

<!--For Visual Studio for Mac Test Explorer we need this reference here-->
<ItemGroup>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
</ItemGroup>

<ItemGroup>
<None Include="Policies/*.rego" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>

0 comments on commit 9158360

Please sign in to comment.