Microsoft MVP성태의 닷넷 이야기
닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS) [링크 복사], [링크+제목 복사],
조회: 7903
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)

가령, 이런 식으로 Web API를 노출한 경우,

[HttpPost("{file}")]
public async Task Post(string file)
{
    var request = HttpContext.Request;
    var stream = request.Body;
    var buffer = new byte[Convert.ToInt32(request.ContentLength)];
    await stream.ReadAsync(buffer, 0, buffer.Length);
    await System.IO.File.WriteAllBytesAsync(file, buffer);
}

이것에 약 28.6MB 정도(정확히는 30,000,000 바이트)를 초과하는 파일을 Post하는 경우 이런 오류가 발생할 수 있습니다.

PS C:\temp> (New-Object System.Net.WebClient).UploadData('http://localhost:21000/weatherforecast/test.zip', 'POST', [System.IO.File]::ReadAllBytes('c:\temp\test.zip'))
Exception calling "UploadData" with "3" argument(s): "The remote server returned an error: (500) Internal Server Error."
At line:1 char:1
+ (New-Object System.Net.WebClient).UploadData('http://localhost:21000/ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

또는, "Bad Request"로 나오기도 하고,

PS C:\temp> (New-Object System.Net.WebClient).UploadData('http://localhost:21000/weatherforecast/test.zip', 'POST', [System.IO.File]::ReadAllBytes('c:\temp\test.zip'))
Exception calling "UploadData" with "3" argument(s): "The remote server returned an error: (400) Bad Request."
At line:1 char:1
+ (New-Object System.Net.WebClient).UploadData('http://localhost:21000 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException


또는 메시지가 좀 더 직관적인 경우도 있습니다.

"The remote server returned an error: (413) Request Entity Too Large."

만약 해당 Web App을 디버깅 중이거나, 로그 파일을 본다면 동시에 아래와 같은 오류 메시지가 출력될 것입니다.

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.

Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Request body too large.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.OnReadStarting()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryStart()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.ReadAsyncInternal(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 buffer, CancellationToken cancellationToken)
   at net_build_helper.ValuesController.ReadAllBytes(Int32 contentLength)
   at net_build_helper.ValuesController.Post(String mode)
   ...[생략]...

원인은, 당연하겠지만 입력 크기의 제한에 걸렸기 때문입니다. 그리고 해결 방법은, Kestrel로 호스팅했느냐, IIS로 호스팅했느냐에 따라 다릅니다.

그렇다면 현재 호스팅 환경은 어떻게 알 수 있을까요? 배포 환경이라면, IIS에 명시적으로 올리지 않는 한 Kestrel로 호스팅되고 있을 것입니다. 반면, Visual Studio에서 개발 중이라면 디버그 타깃을 보면 됩니다.

vs_debug_target_1.png

저기에 "IISExpress"로 선택돼 있다면 IIS 호스팅이고, 그 외의 것은 모두 Kestrel로 호스팅된다고 보면 됩니다.




우선, Kestrel로 호스팅하고 있는 경우의 대처를 볼까요? .NET 8 Web App 프로젝트라면 Program.cs 파일에서 다음과 같은 옵션을 주면 됩니다.

using System.Diagnostics;

namespace WebApplication1;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.WebHost.ConfigureKestrel(options =>
        {
            options.Limits.MaxRequestBodySize = 50 * 1024 * 1024;
        });

        // ...[생략]...

        app.Run();
    }
}

KestrelServerOptions.Limits.MaxRequestBodySize 속성의 기본값은 30,000,000 바이트이므로 위의 경우에는 50MB로 늘린 사례입니다.

참고로, ConfigureKestrel 말고 UseKestrel로 설정해도 됩니다.

builder.WebHost.UseKestrel((options) =>
{
    options.Limits.MaxRequestBodySize = 50 * 1024 * 1024;
});

단지, 이렇게 한 경우에는 명시적으로 Kestrel Web Server를 사용하겠다는 의미이므로, 해당 웹 앱을 IIS에서 호스팅하면 안 됩니다. 만약 그렇게 되면 app.Run 시점에 다음과 같은 예외가 발생합니다.

System.InvalidOperationException
  HResult=0x80131509
  Message=Application is running inside IIS process but is not configured to use IIS server.
  Source=Microsoft.AspNetCore.Server.IIS
  StackTrace:
   at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   ...[생략]...

따라서 강제로 Kestrel로 호스팅해야 할 목적이 아니라면, 가능한 ConfigureKestrel로 옵션을 바꾸는 것이 좋고, 그런 경우 설령 IIS(Express)에서 실행하더라도 ConfigureKestrel 코드를 수행하지 않고 그냥 무시하는 수준에서 그칩니다.




자, 그럼 IIS(Express)라면 어떻게 해야 할까요?

IIS는 독립적인 Web Server이고, .NET 런타임에 앞서 web.config의 설정에 따른 제어를 받습니다. 실제로, 위의 Upload 테스트를 Kestrel 호스팅 환경에서 해보면, 요청이 적어도 Web API까지는 진입을 하고 ReadAsync로 읽어내는 중에 "Request Entity Too Large" 예외가 발생하지만, IIS에서는 닷넷 코드로 진입하기 전에 요청이 거부됩니다.

다시 말해, 닷넷 코드에서 MaxRequestBodySize를 변경해 봤자 IIS 입장에서는 그 사실을 알 수 없으므로 아무런 효과가 없습니다. 결국 위의 예제에 다음과 같이 코드를 추가해,

using Microsoft.AspNetCore.Server.IIS;

// ...[생략]...

builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = 50 * 1024 * 1024; // 50MB
});

실행해 보면, 여전히 "Request Entity Too Large" 예외가 발생합니다. 반면, web.config에 관련 설정을 해두면,

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="1073741824" />
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

50MB까지의 요청을 잘 받아들입니다. 아니, 그런데 maxAllowedContentLength에는 100MB를 설정했는데 왜 50MB일까요? 그것은 Configure 코드에서 MaxRequestBodySize를 50MB로 제한했기 때문입니다. 사실 IISServerOptions.MaxRequestBodySize는 초깃값을 web.config의 maxAllowedContentLength로부터 가져옵니다.

정리해 보면, IIS 호스팅인 경우에는 web.config의 maxAllowedContentLength 속성을 상한으로, ASP.NET 코드 내에서 IISServerOptions.MaxRequestBodySize를 통해 maxAllowedContentLength 범위 내에서 변경할 수 있습니다.

따라서 만약 동적으로 변경해야 할 일이 없다면, 그냥 web.config에 설정을 추가하면 되고, 그렇지 않고 코드로 변경해야 한다면 web.config에는 최댓값을 설정한 후 코드로 제어를 하는 식으로 설정하면 됩니다.




어차피, Configure 코드는 다른 호스팅에서는 무시하므로 둘 다 기본으로 코드를 추가해 설정하는 것도 좋은 선택입니다.

long maxRequest = 50 * 1024 * 1024;

builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = maxRequest;
});

builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = maxRequest;
});

저 상태에서 IIS를 위해서만 특별히 web.config에 설정을 추가하는 식으로 관리하면 될 것입니다. 대신 나중에 코드로 값을 변경해도 반영이 안된다는 것에 자칫 헤맬 수 있으므로 web.config에 대해서만 크기를 (uint 타입의 최대 크기인) 4,294,967,295 (약 3.99GB)로 설정하면 될 텐데요, 단지 이런 경우에 문제라면 원치 않는 크기의 요청이 있을 때 IIS 수준에서 걸러지지 않고 닷넷 런타임까지 넘어온다는 점입니다. 어쩔 수 없습니다, 최적의 성능을 원한다면 두 곳 모두 수정하든가 하는 식의 관리 체계를 탄탄하게 마련해야 합니다.

참고로, MaxRequestBodySize 설정은 닷넷 5 이하에서 만들어진 ASP.NET Core Web App 프로젝트라면 Program.cs의 CreateHostBuilder 메서드에 Kestrel 옵션을 적용할 수 있고,

// .NET 5 이하

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.ConfigureKestrel(serverOptions =>
                {
                    serverOptions.Limits.MaxRequestBodySize = 50 * 1024 * 1024;
                });
            });
}

Startup.cs의 ConfigureServices 메서드에서 IIS 옵션을 적용할 수 있습니다.

// .NET 5 이하

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.Configure<IISServerOptions>(options =>
    {
        options.MaxRequestBodySize = 50 * 1024 * 1024;
    });
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 9/26/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13541정성태1/29/20249610VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20249499Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20249306개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20249901닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/202410685닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/202410300닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/202410726닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/202410140닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/202410122닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/202410175닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/202410556닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20249835닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/202410035닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/202410194Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/202410285오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/202410612닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20249751오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20249780오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20249767오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/202410598닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/202410255닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20249930오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....' [1]
13519정성태1/10/20249632닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/202410357닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20249502스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20249649닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...