[ASP.NET Core] 請求大小限制(轉載)
請求大小一般在文件上傳的時候會用到,當然也防止傳過來的參數過大情況。
一、設置請求體的最大值
如果不設置請求體大小默認是 30_000_000 bytes,大約28.6MB,當超出大小時會出現如下錯誤:
錯誤:Failed to read the request form. Request body too large. The max request body size is 30000000 bytes.
解決方案:
builder.WebHost.ConfigureKestrel((context, options) => { //設置最大1G, 這里的單位是byte options.Limits.MaxRequestBodySize = 1073741824; });
如果傳參用的不是表單的形式(如文件上傳)這樣處理是足夠了的,如果是則還需要設置表單的最大長度。
二、設置表單的最大值
如果不設置表單長度默認是 134,217,728 bytes,大約128MB,當超出大小時會出現如下錯誤:
錯誤:Failed to read the request form. Multipart body length limit 134217728 exceeded.
解決方案:
builder.Services.Configure<FormOptions>(option => { //設置最大1G, 這里的單位是byte option.MultipartBodyLengthLimit = 1073741824; });
三、IIS下的配置
如果是掛在IIS下,還需如下操作:
- 修改C:\Windows\System32\inetsrv\config\schema\IIS_schema.xml中maxAllowedContentLength的大小;
- 修改項目web.config配置system.webServer/serverRuntime/maxRequestEntityAllowed的大小;
- 修改項目web.config配置system.web/httpRuntime/maxRequestLength的大小;
- 重啟IIS。
文章轉載于:https://www.helloworld.net/p/9291788101
下面是github的issue,基本上可以解決大部分請求遇到的大小限制問題,可根據自己需要添加相關代碼:
https://github.com/dotnet/aspnetcore/issues/20369
1. IIS content length limit
The default request limit (maxAllowedContentLength) is 30,000,000 bytes, which is approximately 28.6MB. Customize the limit in the web.config file:
<system.webServer>
<security>
<requestFiltering>
<!-- Handle requests up to 1 GB -->
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
Note: Without this application running on IIS would not work.
2. ASP.NET Core Request length limit:
For application running on IIS:
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
For application running on Kestrel:
services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = int.MaxValue; // if don't set default value is: 30 MB
});
3. Form's MultipartBodyLengthLimit
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue; // if don't set default value is: 128 MB
x.MultipartHeadersLengthLimit = int.MaxValue;
});
Adding all the above options will solve the problem related to the file upload with size more than 30.0 MB.

浙公網安備 33010602011771號