增加 Kestrel 中的上传请求长度限制
Increase upload request length limit in Kestrel
我是 运行 一个 ASP.NET 核心网络应用程序,想要上传大文件。
我知道当 运行 IIS 时,可以通过 web.config
:
更改限制
<httpRuntime maxRequestLength="1048576" />
...
<requestLimits maxAllowedContentLength="1073741824" />
如何在 运行 新的 ASP.NET Core Kestrel Web 服务器上做同样的事情?
我得到异常 "Request body too large."
我发现 this helpful announcement 确认从 ASP.NET Core 2.0 开始存在 28.6 MB 的主体大小限制,但更重要的是展示了如何绕过它!
总结一下:
对于单个控制器或操作,使用 [DisableRequestSizeLimit]
attribute to have no limit, or the [RequestSizeLimit(100_000_000)]
指定自定义限制。
要全局更改它,在 BuildWebHost()
方法内,在 Program.cs
文件内,添加下面的 .UseKestrel
选项:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
}
为了更加清楚,您还可以参考 Kestrel options documentation。
适用于ASP.NET Core 2.0,但我想提供.NET Core 3.x web API.
的解决方案
您在 program.cs
中的代码必须像这样才能工作:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
});
});
}
我是 运行 一个 ASP.NET 核心网络应用程序,想要上传大文件。
我知道当 运行 IIS 时,可以通过 web.config
:
<httpRuntime maxRequestLength="1048576" />
...
<requestLimits maxAllowedContentLength="1073741824" />
如何在 运行 新的 ASP.NET Core Kestrel Web 服务器上做同样的事情?
我得到异常 "Request body too large."
我发现 this helpful announcement 确认从 ASP.NET Core 2.0 开始存在 28.6 MB 的主体大小限制,但更重要的是展示了如何绕过它!
总结一下:
对于单个控制器或操作,使用 [DisableRequestSizeLimit]
attribute to have no limit, or the [RequestSizeLimit(100_000_000)]
指定自定义限制。
要全局更改它,在 BuildWebHost()
方法内,在 Program.cs
文件内,添加下面的 .UseKestrel
选项:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
}
为了更加清楚,您还可以参考 Kestrel options documentation。
您在 program.cs
中的代码必须像这样才能工作:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
});
});
}