From 5b90028fe370c68e93fb20153880bd97cce1905d Mon Sep 17 00:00:00 2001 From: John Luo Date: Tue, 2 Oct 2018 16:21:45 -0700 Subject: [PATCH] Expose status code of BadHttpRequestException --- samples/SampleApp/Startup.cs | 20 +++++++++++++++++++- src/Kestrel.Core/BadHttpRequestException.cs | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/samples/SampleApp/Startup.cs b/samples/SampleApp/Startup.cs index 166b47a932..6cc37cc58a 100644 --- a/samples/SampleApp/Startup.cs +++ b/samples/SampleApp/Startup.cs @@ -11,6 +11,8 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Https.Internal; using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal; using Microsoft.Extensions.Configuration; @@ -24,8 +26,24 @@ namespace SampleApp { var logger = loggerFactory.CreateLogger("Default"); + // Add an exception handler that prevents throwing due to large request body size + app.Use(async (context, next) => + { + // Limit the request body to 1kb + context.Features.Get().MaxRequestBodySize = 1024; + + try + { + await next.Invoke(); + } + catch (BadHttpRequestException ex) when (ex.StatusCode == StatusCodes.Status413RequestEntityTooLarge) { } + }); + app.Run(async context => { + // Drain the request body + await context.Request.Body.CopyToAsync(Stream.Null); + var connectionFeature = context.Connection; logger.LogDebug($"Peer: {connectionFeature.RemoteIpAddress?.ToString()}:{connectionFeature.RemotePort}" + $"{Environment.NewLine}" @@ -152,7 +170,7 @@ namespace SampleApp // options.ThreadCount = 4; }); } - + return hostBuilder.Build().RunAsync(); } diff --git a/src/Kestrel.Core/BadHttpRequestException.cs b/src/Kestrel.Core/BadHttpRequestException.cs index db3e9f0dd4..7324335665 100644 --- a/src/Kestrel.Core/BadHttpRequestException.cs +++ b/src/Kestrel.Core/BadHttpRequestException.cs @@ -29,7 +29,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core } } - internal int StatusCode { get; } + public int StatusCode { get; } internal StringValues AllowedHeader { get; }