ASP.NET Core 2.0中如何更改Http請求的maxAllowedContentLength最大值


Web.config中的maxAllowedContentLength這個屬性可以用來設置Http的Post類型請求可以提交的最大數據量,超過這個數據量的Http請求ASP.NET Core會拒絕並報錯,由於ASP.NET Core的項目文件中取消了Web.config文件,所以我們無法直接在visual studio的解決方案目錄中再來設置maxAllowedContentLength的屬性值。

 

但是在發布ASP.NET Core站點后,我們會發現發布目錄下有一個Web.config文件:

 

我們可以在發布后的這個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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM