Keeps the JSON error envelope for callers without a content preference.

This commit is contained in:
BinaryAlley committed 2026-11-07 18:45:02 +02:00
1 parent e2c705d822
commit a88e7ebc4e
2 files changed
+51 -2

No files matched your search

@@ -81,8 +81,19 @@ public class ExceptionHandlingMiddleware
serverUnreachable = IsApiOutage(ex),
errorMessage = _stringLocalizer["InternalServerError"].Value
});
else if (IsNavigationRequest(context))
else if (IsExplicitNavigationRequest(context))
await WriteHtmlErrorResponseAsync(context, (int)HttpStatusCode.InternalServerError, _stringLocalizer["InternalServerError"].Value).ConfigureAwait(false);
else if (IsNavigationRequest(context))
{
// A caller that states no preference is not necessarily a browser, so it keeps the historical JSON envelope instead of
// receiving an HTML page it cannot consume.
await WriteJsonResponseAsync(context, new
{
success = false,
serverUnreachable = IsApiOutage(ex),
errorMessage = _stringLocalizer["InternalServerError"].Value
});
}
else
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.InternalServerError).ConfigureAwait(false);
}
@@ -348,6 +359,22 @@ public class ExceptionHandlingMiddleware
|| string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Checks if the current request explicitly identifies itself as a browser navigation, rather than merely stating no preference.
/// </summary>
/// <remarks>
/// A caller that sends no <c>Accept</c> header at all may be a script, a probe, or an API client, so it is not safe to answer it with
/// an HTML page. Only a request that asks for HTML or carries the browser navigation headers is treated as a page here.
/// </remarks>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
/// <returns><see langword="true"/> when the request is explicitly a browser navigation, <see langword="false"/> otherwise.</returns>
private static bool IsExplicitNavigationRequest(HttpContext context)
{
return context.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|| string.Equals(context.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|| string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Writes a JSON response to the client.
/// </summary>
@@ -80,7 +80,8 @@ public class ExceptionHandlingMiddlewareTests
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
// An ordinary bug is not an unreachable server, so the client must not switch to the outage path for it.
Assert.False(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
_mockLogger.Received(1).Log(
LogLevel.Error,
@@ -95,6 +96,7 @@ public class ExceptionHandlingMiddlewareTests
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE");
httpContext.Request.Headers.Accept = "text/html";
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
@@ -112,6 +114,26 @@ public class ExceptionHandlingMiddlewareTests
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndRequestStatesNoPreference_ShouldWriteFailureJson()
{
// Arrange
// A caller that sends no Accept header is not proven to be a browser, so it keeps the historical JSON envelope.
DefaultHttpContext httpContext = CreateHttpContext();
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Contains("application/json", httpContext.Response.ContentType);
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.False(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndRawRequest_ShouldWriteStatusCodeWithoutBody()
{