天天看點

ASP.NET Core中如何更改檔案上傳大小限制maxAllowedContentLength屬性值

Web.config中的maxAllowedContentLength這個屬性可以用來設定Http的Post類型請求可以送出的最大資料量,超過這個資料量的Http請求ASP.NET Core會拒絕并報錯,由于ASP.NET Core的項目檔案中取消了Web.config檔案,是以我們無法直接在visual studio的解決方案目錄中再來設定maxAllowedContentLength的屬性值。

ASP.NET Core中如何更改檔案上傳大小限制maxAllowedContentLength屬性值

但是在釋出ASP.NET Core站點後,我們會發現釋出目錄下有一個Web.config檔案:

ASP.NET Core中如何更改檔案上傳大小限制maxAllowedContentLength屬性值
ASP.NET Core中如何更改檔案上傳大小限制maxAllowedContentLength屬性值

我們可以在釋出後的這個Web.config檔案中設定maxAllowedContentLength屬性值:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- 1 GB -->
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>           

複制

在ASP.NET Core中maxAllowedContentLength的預設值是30000000,也就是大約28.6MB,我們可以将其最大更改為2147483648,也就是2G。

URL參數太長的配置

當URL參數太長時,IIS也會對Http請求進行攔截并傳回404錯誤,是以如果你的ASP.NET Core項目會用到非常長的URL參數,那麼還要在Web.config檔案中設定maxQueryString屬性值:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxQueryString="302768" maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>           

複制

然後還要在項目Program類中使用UseKestrel方法來設定MaxRequestLineSize屬性,如下所示:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBufferSize = 302768;
                options.Limits.MaxRequestLineSize = 302768;
            })
            .UseStartup<Startup>();
}           

複制

可以看到,上面的代碼中我們還設定了MaxRequestBufferSize屬性,這是因為MaxRequestBufferSize屬性的值不能小于MaxRequestLineSize屬性的值,如果隻将MaxRequestLineSize屬性設定為一個很大的數字,那麼會導緻MaxRequestBufferSize屬性小于MaxRequestLineSize屬性,這樣代碼會報錯。

送出表單(Form)的Http請求

對于送出表單(Form)的Http請求,如果送出的資料很大(例如有檔案上傳),還要記得在Startup類的ConfigureServices方法中配置下面的設定:

public void ConfigureServices(IServiceCollection services)
{
  services.Configure<FormOptions>(x =>
  {
      x.ValueLengthLimit = int.MaxValue;
      x.MultipartBodyLengthLimit = int.MaxValue;
      x.MultipartHeadersLengthLimit = int.MaxValue;
  });

  services.AddMvc();
}           

複制

另一個參考辦法

The other answers solve the IIS restriction. However, as of ASP.NET Core 2.0, Kestrel server also imposes its own default limits.

Github of KestrelServerLimits.cs

Announcement of request body size limit and solution (quoted below)

MVC Instructions

If you want to change the max request body size limit for a specific MVC action or controller, you can use the RequestSizeLimit attribute. The following would allow MyAction to accept request bodies up to 100,000,000 bytes.

[HttpPost]
[RequestSizeLimit(100_000_000)]
public IActionResult MyAction([FromBody] MyViewModel data)
{           

複制

[DisableRequestSizeLimit] can be used to make request size unlimited. This effectively restores pre-2.0.0 behavior for just the attributed action or controller.

Generic Middleware Instructions

If the request is not being handled by an MVC action, the limit can still be modified on a per request basis using the IHttpMaxRequestBodySizeFeature. For example:

app.Run(async context =>
{
    context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 100_000_000;           

複制

MaxRequestBodySize is a nullable long. Setting it to null disables the limit like MVC's [DisableRequestSizeLimit].

You can only configure the limit on a request if the application hasn’t started reading yet; otherwise an exception is thrown. There’s an IsReadOnly property that tells you if the MaxRequestBodySize property is in read-only state, meaning it’s too late to configure the limit.

Global Config Instructions

If you want to modify the max request body size globally, this can be done by modifying a MaxRequestBodySize property in the callback of either UseKestrel or UseHttpSys. MaxRequestBodySize is a nullable long in both cases. For example:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = null;
            })
            .Build();
}           

複制

or

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseHttpSys(options =>
            {
                options.MaxRequestBodySize = null;
            })
            .Build();
}           

複制

上面兩種方法設定MaxRequestBodySize屬性為null,表示伺服器不限制Http請求送出的最大資料量,其預設值為30000000(位元組),也就是大約28.6MB。

參考文章:Increase upload file size in Asp.Net core