ASP.NET Core中如何更改文件上传大小限制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

posted @ 2021-06-01 22:12  跟着阿笨一起玩.NET  阅读(773)  评论(0编辑  收藏  举报