前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ASP.NET Core中如何更改文件上传大小限制maxAllowedContentLength属性值

ASP.NET Core中如何更改文件上传大小限制maxAllowedContentLength属性值

作者头像
跟着阿笨一起玩NET
发布2021-06-09 20:07:48
4.5K0
发布2021-06-09 20:07:48
举报

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属性值:

代码语言:javascript
复制
<?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属性值:

代码语言:javascript
复制
<?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属性,如下所示:

代码语言:javascript
复制
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方法中配置下面的设置:

代码语言:javascript
复制
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.

代码语言:javascript
复制
[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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-06-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档