我的API Controller 上有[RequestSizeLimit],它可以按预期工作:大于指定限制的请求将被拒绝。

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

问题是,抛出了一个异常:
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)

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

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

最佳答案

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;
        }
    }
}

并在Startup.cs的Configure中注册它:
public void Configure(IApplicationBuilder app)
{
    ...
    app.UseMiddleware<ExceptionMiddleware>();
    ...
}

或者,您也可以使用Exception filter

关于c# - NETt 2.1.401的RequestSizeLimitAttribute : HTTP 500 instead of 413 in ASP.,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52243903/

10-11 02:11