RequestSizeLimitAttribute: HTTP 500 而不是 ASP.NET Core 2.1.401 中的 413

Pav*_*syn 5 c# asp.net-core

我有[RequestSizeLimit]我的 API 控制器,它有点像预期的那样工作:大于指定限制的请求被拒绝。

    [HttpPut]
    [RequestSizeLimit(120_000_000)]
    public async Task<IActionResult> Put(IFormCollection form)
    {
       ...
    }
Run Code Online (Sandbox Code Playgroud)

问题是,抛出异常:

Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Request body too large.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1MessageBody.ForContentLength.OnReadStarting()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryInit()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 buffer, CancellationToken cancellationToken)
Run Code Online (Sandbox Code Playgroud)

因此返回 HTTP 500,但我希望返回 413 或 400。而且我不希望出现异常,因为这是完全正常的情况。

找不到关于此的任何文档。对于过大的请求,返回 413 的正确方法是什么?

Ale*_*bov 6

Kestrel 使用 413 Payload Too Large 响应进行响应,但 HttpSys 使用通用 500 Internal Server Error 响应进行响应。我假设你使用第二个。在这种情况下,您可以实现异常处理中间件来处理这种情况:

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            HandleExceptionAsync(httpContext, ex);
        }
    }

    private static void HandleExceptionAsync(HttpContext context, Exception exception)
    {
        if (exception is BadHttpRequestException badRequestException && badRequestException.Message == "Request body too large.")
        {
            context.Response.StatusCode = (int) HttpStatusCode.RequestEntityTooLarge;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在Startup.cs中的Configure中注册:

public void Configure(IApplicationBuilder app)
{
    ...
    app.UseMiddleware<ExceptionMiddleware>();
    ...
}
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您还可以使用异常过滤器