ASP.NET Cpre アプリケーションのデバッグを行っていると 404.13 エラーが表示され、調べてみると、アップロードしたファイルのサイズが大きすぎたようです。
規定値は 30 MB らしいのですが、この上限を変更します。
環境
- Visual Studio 2017
- ASP.NET Core 2.1
IIS Express を使用している場合
IIS Express の設定を変更します。
applicationhost.config
の設定を変更する方法と、web.config
を作成する方法の二通りあるようです。
applicationhost.config の変更する方法
Visual Studio 2017 の場合、applicationhost.config
は以下の場所にあります。
[ソリューションフォルダ]\.vs\config\applicationhost.config
requestFiltering
セクションに以下のような設定を追加します。
<!-- This will handle requests up to 50MiB -->
<requestLimits maxAllowedContentLength="52428800" />
web.config を作成する方法
applicationhost.config
は .vs
の配下にあるので、ソリューション内の全プロジェクトに影響がありますし、そもそも Git などのソースコード管理から除外している場合が多いと思うので、web.config
を作成するほうが良いかなと思います。
以下に詳しく説明されていたので、そのまま引用します。
ASP.NET Core のプロジェクト配下に web.config
というファイルを作成し、以下の内容を記述します。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- To customize the asp.net core module uncomment and edit the following section.
For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
<system.webServer>
<handlers>
<remove name="aspNetCore"/>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
<security>
<requestFiltering>
<!-- This will handle requests up to 50MiB -->
<requestLimits maxAllowedContentLength="52428800" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
Kestrel を使用している場合
IIS Express ではなく Kestrel を使用している場合は、program.cs
の CreateDefaultBuilder
で、MaxRequestBodySize
の値を設定すれば OK です。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = 52428800; // 50MiB
});
}
ただし、この場合はプロジェクト内全てに影響するグローバルな設定なので、Controller ごとに上限を変更したい場合は、後述するように Attribute を使います。
特定の Controller でのみ上限を変更したい場合
Controller ごとにファイルアップロードサイズの上限を変更したい場合は、以下のように Controller のアクションメソッドに Attribute を追加します。
サイズを指定する場合は RequestSizeLimit
を、無制限にしたい場合は DisableRequestSizeLimit
を追加します。
[HttpPost]
[RequestSizeLimit(40000000)]
public async Task<IActionResult> UploadFiles(IFormFile file)
{
//TODO: Save file
}
サイズを無制限にしたい場合です。
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> UploadFiles(IFormFile file)
{
//TODO: Save file
}
参考 URL
- http://www.talkingdotnet.com/how-to-increase-file-upload-size-asp-net-core/
- https://docs.microsoft.com/ja-jp/aspnet/core/host-and-deploy/iis/?view=aspnetcore-2.1&tabs=aspnetcore2x#webconfig-file
- https://stackoverflow.com/questions/46510836/http-error-404-13-asp-net-core-2-0
- https://qiita.com/k_saito/items/790884389e0c0611b258