KestrelHttpServer 256 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. commit 5b90028fe370c68e93fb20153880bd97cce1905d
  2. Author: John Luo <[email protected]>
  3. Date: Tue Oct 2 16:21:45 2018 -0700
  4. Expose status code of BadHttpRequestException
  5. diff --git a/samples/SampleApp/Startup.cs b/samples/SampleApp/Startup.cs
  6. index 166b47a9327..6cc37cc58a3 100644
  7. --- a/samples/SampleApp/Startup.cs
  8. +++ b/samples/SampleApp/Startup.cs
  9. @@ -11,6 +11,8 @@ using System.Threading.Tasks;
  10. using Microsoft.AspNetCore.Builder;
  11. using Microsoft.AspNetCore.Hosting;
  12. using Microsoft.AspNetCore.Http;
  13. +using Microsoft.AspNetCore.Http.Features;
  14. +using Microsoft.AspNetCore.Server.Kestrel.Core;
  15. using Microsoft.AspNetCore.Server.Kestrel.Https.Internal;
  16. using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
  17. using Microsoft.Extensions.Configuration;
  18. @@ -24,8 +26,24 @@ namespace SampleApp
  19. {
  20. var logger = loggerFactory.CreateLogger("Default");
  21. + // Add an exception handler that prevents throwing due to large request body size
  22. + app.Use(async (context, next) =>
  23. + {
  24. + // Limit the request body to 1kb
  25. + context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 1024;
  26. +
  27. + try
  28. + {
  29. + await next.Invoke();
  30. + }
  31. + catch (BadHttpRequestException ex) when (ex.StatusCode == StatusCodes.Status413RequestEntityTooLarge) { }
  32. + });
  33. +
  34. app.Run(async context =>
  35. {
  36. + // Drain the request body
  37. + await context.Request.Body.CopyToAsync(Stream.Null);
  38. +
  39. var connectionFeature = context.Connection;
  40. logger.LogDebug($"Peer: {connectionFeature.RemoteIpAddress?.ToString()}:{connectionFeature.RemotePort}"
  41. + $"{Environment.NewLine}"
  42. @@ -152,7 +170,7 @@ namespace SampleApp
  43. // options.ThreadCount = 4;
  44. });
  45. }
  46. -
  47. +
  48. return hostBuilder.Build().RunAsync();
  49. }
  50. diff --git a/src/Kestrel.Core/BadHttpRequestException.cs b/src/Kestrel.Core/BadHttpRequestException.cs
  51. index db3e9f0dd42..7324335665a 100644
  52. --- a/src/Kestrel.Core/BadHttpRequestException.cs
  53. +++ b/src/Kestrel.Core/BadHttpRequestException.cs
  54. @@ -29,7 +29,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core
  55. }
  56. }
  57. - internal int StatusCode { get; }
  58. + public int StatusCode { get; }
  59. internal StringValues AllowedHeader { get; }