更新时间:2023-02-17 10:00:14
Kestrel响应为413 Payload Too Large,但HttpSys响应为通用500 Internal Server Error响应.我假设您使用第二个.在这种情况下,您可以实现异常处理中间件来处理这种情况:
Kestrel responds with a 413 Payload Too Large response, but HttpSys responds with a generic 500 Internal Server Error response. I assume you use the second one. In this case you can implement Exception handling middelware to handle this case:
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"中注册它:
And register it in Configure in Startup.cs:
public void Configure(IApplicationBuilder app)
{
...
app.UseMiddleware<ExceptionMiddleware>();
...
}
您也可以使用异常过滤器