Azure Linux Web App请求过大返回502,能否配置为返回413状态码?
解决Linux App Service返回502而非413的问题
原因分析
Azure Linux App Service默认使用nginx作为反向代理,其内置配置会限制请求体大小。如果请求超出nginx的默认限制,它会直接中断请求而非转发给Kestrel处理,最终导致用户收到502错误,而非Kestrel配置的413响应。
解决方案
1. 自定义nginx配置,调整请求体大小限制
在ASP.NET Core项目根目录下创建.deployment文件夹,在该文件夹内新建nginx.conf文件,写入以下配置:
server { listen 8080; location / { proxy_pass http://localhost:5000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $remote_addr; # 与Kestrel配置保持一致的请求体大小限制 client_max_body_size 30M; } }
该配置将nginx的请求体限制设为30M,确保大请求能被转发到Kestrel,由Kestrel返回预期的413响应。
2. 添加中间件捕获413异常
在Program.cs中,在app.UseRouting()之前添加以下中间件,确保Kestrel抛出的请求体过大异常能被正确捕获并返回标准413响应:
app.Use(async (context, next) => { try { await next(); } catch (BadHttpRequestException ex) when (ex.StatusCode == StatusCodes.Status413RequestEntityTooLarge) { context.Response.StatusCode = StatusCodes.Status413RequestEntityTooLarge; await context.Response.WriteAsync("Request Entity Too Large"); } });
3. 部署验证
将修改后的代码和nginx配置一同部署到Linux App Service,测试上传超过30M的请求,此时应返回明确的413状态码。
内容的提问来源于stack exchange,提问作者GWigWam
相关产品推荐
相关产品推荐

