ASP.NET Core 調整請求的大小限制

在夾帶附件呼叫 API 上傳時發生下面的錯誤:
    
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-ed1b2b13bbcdab1111d3d222dedcb4e7-9f929eb4af395059-00",
  "errors": {
    "": [
      "Failed to read the request form. Request body too large. The max request body size is 30000000 bytes."
    ]
  }
}
    

簡單來說就是一個請求的大小超過 28.6MB,需要增加限制的大小。

調整 Kestrel 限制

在 ASP.NET Core 專案中預設會自帶 Kestrel 網頁伺服器,平時直接執行程式、使用 dotnet watch 等的就是使用 Kestrel 來啟動。

可以在 Program.cs 檔案中增加下面的程式碼來將上限調整到 100 MB
    
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.Limits.MaxRequestBodySize = 100 * 1024 * 1024;
});
    

調整 IIS 限制

可以在 Program.cs 檔案中增加下面的程式碼來將上限調整到 100 MB
    
builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = int.MaxValue;
});
    

留言