diff --git a/src/Wemogy.AspNet.Tests/Middlewares/ErrorHandlerMiddlewareTests.cs b/src/Wemogy.AspNet.Tests/Middlewares/ErrorHandlerMiddlewareTests.cs index 7d1749a..0da5066 100644 --- a/src/Wemogy.AspNet.Tests/Middlewares/ErrorHandlerMiddlewareTests.cs +++ b/src/Wemogy.AspNet.Tests/Middlewares/ErrorHandlerMiddlewareTests.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Net; +using System.Threading; using System.Threading.Tasks; using FluentAssertions; using FluentValidation; @@ -84,4 +85,33 @@ await middleware.InvokeAsync( // Assert context.Response.StatusCode.Should().Be((int)HttpStatusCode.BadRequest); } + + [Fact] + public async Task CanceledRequestShouldBeIgnored() + { + // Arrange + var abortedCts = new CancellationTokenSource(); + var context = new DefaultHttpContext + { + RequestServices = new ServiceCollection() + .AddLogging() + .BuildServiceProvider(), + RequestAborted = abortedCts.Token + }; + var next = new RequestDelegate( + c => + { + // simulate that somewhere in the pipeline we are checking for cancellation + c.RequestAborted.ThrowIfCancellationRequested(); + return Task.CompletedTask; + }); + var middleware = new ErrorHandlerMiddleware(next); + + // Act + abortedCts.Cancel(); // simulate that the request was aborted + var exception = await Record.ExceptionAsync(() => middleware.InvokeAsync(context)); + + // Assert + exception.Should().BeNull(); + } } diff --git a/src/Wemogy.AspNet/Middlewares/ErrorHandlerMiddleware.cs b/src/Wemogy.AspNet/Middlewares/ErrorHandlerMiddleware.cs index 54c5188..b943474 100644 --- a/src/Wemogy.AspNet/Middlewares/ErrorHandlerMiddleware.cs +++ b/src/Wemogy.AspNet/Middlewares/ErrorHandlerMiddleware.cs @@ -1,3 +1,4 @@ +using System; using System.Net; using System.Threading.Tasks; using FluentValidation; @@ -66,6 +67,17 @@ public async Task InvokeAsync(HttpContext context) response.StatusCode = (int)HttpStatusCode.BadRequest; await response.WriteAsJsonAsync(exception.Errors); } + + // Catch OperationCanceledException, when the request is aborted + catch (OperationCanceledException) + { + if (context.RequestAborted.IsCancellationRequested) + { + return; + } + + throw; + } } } }