Asp.Net Core上传大文件请求体限制设置

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

posted @ 2020-09-17 20:58  我的伙伴  阅读(1091)  评论(0编辑  收藏  举报