IIS進程內部署時
1. Web.Config的<system.webServer>節點下增加
<security> <requestFiltering> <requestLimits maxAllowedContentLength="20971520" /> </requestFiltering> </security>
2. 配置IISServerOptions選項
services.Configure<IISServerOptions>(options => { options.MaxRequestBodySize = 20971520; // 20M });
若使用IIS托管時,可以根據請求響應的狀態碼確定是IIS報錯(413)還是asp.net core框架(500)報錯。
Kestrel部署
1. 配置KestrelServerOptions選項
services.Configure<KestrelServerOptions>(options => { options.Limits.MaxRequestBodySize = 20971520; // 20M });
全局設置(不區分部署方式)
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 20971520; // 20M
通過獲取IHttpMaxRequestBodySizeFeature接口的實現類來設置最大請求體大小,該接口在不同的部署環境中具體的實現類不一樣,
IIS中為:
HTTP1/2 Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT<Microsoft.AspNetCore.Hosting.HostingApplication.Context>
Kestrel中為:
HTTP1 Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection<Microsoft.AspNetCore.Hosting.HostingApplication.Context>
HTTP2 Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Stream<Microsoft.AspNetCore.Hosting.HostingApplication.Context>
這幾個實現類中都實現了IHttpMaxRequestBodySizeFeature接口
需要注意的是該設置方式必須在讀取請求體之前設置。
internal class Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody
protected override void OnReadStarting()
{
long contentLength = this._contentLength;
long? maxRequestBodySize = this._context.MaxRequestBodySize;
if (contentLength > maxRequestBodySize.GetValueOrDefault() & maxRequestBodySize != null)
{
BadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTooLarge);
}
}