본문 바로가기
ASP.NET Core

ASP.NET Core] HTTP error status code 404 처리

by Fastlane 2023. 5. 12.
728x90
반응형

endpoint가 없는 /files 경로를 호출한 경우 404 error status code를 처리할 수 있는 방법을 살펴보자. 

1. UseStatusCodePages

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

app.UseStatusCodePages();

엔드포인트를 찾을 수 없다는 브라우저 종속 오류 메시지가 반환된다. 

2.UseStatusCodePages(response content type, text를 지정하는 방법)

using static System.Net.Mime.MediaTypeNames;

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

app.UseStatusCodePages(Text.Plain, "Status Code Page: {0}");

반응형

3. UseStatusCodePagesWithRedirects

Program.cs

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

app.UseStatusCodePagesWithRedirects("/Home/HandleError/{0}");

HomeController.cs

        [Route("/Home/HandleError/{code:int}")]
        public IActionResult HandleError(int code)
        {
            ViewData["ErrorMessage"] = $"Error occurred. The ErrorCode is: {code}";
            return View("~/Views/Shared/HandleError.cshtml");
        }

HandleError.cshtml

@{
}

<h1 class="text-danger">@ViewData["ErrorMessage"]</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

client에 302-Found status code 반환

error handling point로 redirect, error정보를 display하고 http 200 반환

4. UseStatusCodePagesWithReExecute

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}


app.UseStatusCodePagesWithReExecute("/Home/HandleError/{0}");

다른 엔드포인트로 redirect하지 않고, 상태코드가 유지됨

 

728x90
반응형

댓글