Home > OS >  Custom 404 page on Azure App Service Linux asp.net core webapp
Custom 404 page on Azure App Service Linux asp.net core webapp

Time:09-28

Like the long title say: how can I redirect all the non-existing requests to a /404 page?

I try the web.config solution, the routes.json and/or the staticwebapp.config.json solution, both in /site/wwwroot folder (where dll and exe are) and in /site/wwwroot/wwwroot, but without success.

It is an Asp,net core razor Pages webapp, .net core 6, deployed on App Service Linux

Thanks

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" path="/404" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
</configuration>
{
  "responseOverrides": {
    "404": {
      "rewrite": "/404"
    }
  },
  "platformErrorOverrides": [
    {
      "errorType": "NotFound",
      "serve": "/404"
    }
  ]
}

CodePudding user response:

To add custom Error page in ASP.Net Core Web App, please check the below workaround.

In Program.cs file , add UseStatusCodePagesWithReExecute middleware to generate the unique error page.

My Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
else
{
    app.UseStatusCodePagesWithReExecute("/Error/{0}");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Add a new Controller, name it as HandleErrorController and add a view with name Error.cshtml.

My HandleErrorController.cs

using Microsoft.AspNetCore.Mvc;
namespace CustomErrorPage.Controllers
{
    public class HandleErrorController : Controller
    {     
      
        [Route("Error/{statusCode}")]
        public IActionResult StatusCodeHandler(int StatusCode)
        {
            switch (StatusCode)
            {
                case 404:
                    ViewBag.StatusErrorMessage = "Sorry, the requested resource is not available";
                    break;
            }
            return View("Error");
        }
    }
}

My Error.cshtml

@{
    ViewBag.Title = "Not Found";
}

<h1>@ViewBag.StatusErrorMessage</h1>
<a asp-action="index" asp-controller="home">
    Navigate to the home page
</a>

Re-Deploy the WebApp.

Navigate to Azure portal => Your Web App => Configuration => Application Settings, add the below Environment variable

ASPNETCORE_ENVIRONMENT

enter image description here

Output: enter image description here

Thanks to KudVenkat for the clear Explaination

  • Related