mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 22:11:10 +00:00
Returns client errors for JSON binding failures
This commit is contained in:
1 parent
bb746eef4e
commit
dab6bac9a7
8 files changed
+520
No files matched your search
@@ -29,4 +29,9 @@ public static class HttpContextItemKeys
|
||||
/// The <c>Cache-Control</c> value chosen by the endpoint, restored when the response starts.
|
||||
/// </summary>
|
||||
public const string CACHE_CONTROL = "CacheControl";
|
||||
|
||||
/// <summary>
|
||||
/// The key under which the flag indicating that the endpoint bound its request and started executing is stored.
|
||||
/// </summary>
|
||||
public const string ENDPOINT_STARTED = "EndpointStarted";
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Nemera.Presentation.Web.Common.Http;
|
||||
|
||||
/// <summary>
|
||||
/// Marks an endpoint whose malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope.
|
||||
/// </summary>
|
||||
public sealed class JsonBindingFailureClientErrorMetadata
|
||||
{
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Nemera.Presentation.Web.Common.Exceptions;
|
||||
using Nemera.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
@@ -61,6 +63,11 @@ public class ExceptionHandlingMiddleware
|
||||
{
|
||||
await HandleApiExceptionAsync(context, apiException);
|
||||
}
|
||||
catch (JsonException jsonException) when (IsOptedInJsonBindingFailure(context, jsonException))
|
||||
{
|
||||
// The JSON request body failed to bind before the endpoint ran, so the caller sent a body that does not match the request contract.
|
||||
await HandleJsonBindingExceptionAsync(context, jsonException);
|
||||
}
|
||||
catch (Exception ex) // Other cases.
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Error))
|
||||
@@ -100,6 +107,63 @@ public class ExceptionHandlingMiddleware
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a JSON exception is a request body binding failure of an endpoint that opted into client error responses.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <param name="jsonException">The JSON exception thrown while processing the request.</param>
|
||||
/// <returns><see langword="true"/> when the exception is a JSON body binding failure that should be reported as a client error.</returns>
|
||||
private static bool IsOptedInJsonBindingFailure(HttpContext context, JsonException jsonException)
|
||||
{
|
||||
return jsonException is not FastEndpoints.JsonBindException
|
||||
&& !context.Items.ContainsKey(HttpContextItemKeys.ENDPOINT_STARTED)
|
||||
&& context.GetEndpoint()?.Metadata.GetMetadata<JsonBindingFailureClientErrorMetadata>() is not null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a JSON request body that could not be deserialized into the request contract.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <param name="jsonException">The exception thrown while binding the request body.</param>
|
||||
private async Task HandleJsonBindingExceptionAsync(HttpContext context, JsonException jsonException)
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Warning))
|
||||
_logger.LogWarning(jsonException, "The JSON request body could not be deserialized: {Message}", jsonException.Message);
|
||||
|
||||
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced.
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
context.Abort();
|
||||
return;
|
||||
}
|
||||
|
||||
string errorMessage = _stringLocalizer["OneOrMoreValidationErrorsOccurred"].Value;
|
||||
string? trimmedPath = jsonException.Path?.TrimStart('$', '.');
|
||||
string fieldName = string.IsNullOrWhiteSpace(trimmedPath) ? "request" : trimmedPath;
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
await context.Response.WriteAsJsonAsync(
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.1",
|
||||
title = "General.Validation",
|
||||
status = StatusCodes.Status400BadRequest,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = context.Request.Path.ToString(),
|
||||
errors = new Dictionary<string, string[]> { [fieldName] = [errorMessage] },
|
||||
errorMessage
|
||||
},
|
||||
options: null,
|
||||
contentType: "application/problem+json",
|
||||
cancellationToken: context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
else if (IsNavigationRequest(context))
|
||||
await WriteHtmlErrorResponseAsync(context, StatusCodes.Status400BadRequest, errorMessage).ConfigureAwait(false);
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, StatusCodes.Status400BadRequest).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles exceptions specific to the API, including problem details.
|
||||
/// </summary>
|
||||
|
||||
@@ -3,6 +3,8 @@ using FastEndpoints;
|
||||
using Nemera.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Web.Core.Endpoints.Common;
|
||||
@@ -31,6 +33,25 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the endpoint so that malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope.
|
||||
/// </summary>
|
||||
protected void ReportJsonBindingFailuresAsClientErrors()
|
||||
{
|
||||
Metadata(new JsonBindingFailureClientErrorMetadata());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the request as past request binding, so that JSON binding failures can be told apart from JSON failures thrown while the endpoint runs.
|
||||
/// </summary>
|
||||
/// <param name="request">The request bound from the incoming request.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override Task OnBeforeHandleAsync(TRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
HttpContext.Items[HttpContextItemKeys.ENDPOINT_STARTED] = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>Cache-Control</c> header, and remembers the chosen value so that it can be restored after later components overwrite it.
|
||||
/// </summary>
|
||||
|
||||
+1
@@ -41,6 +41,7 @@ public class SaveBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
|
||||
DontAutoTag();
|
||||
Options(options => options.WithTags("Books"));
|
||||
EnableAntiforgery();
|
||||
ReportJsonBindingFailuresAsClientErrors();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user