Custom Error Page in Production for .NET 5.0
Asked Answered
D

3

9

I am trying to implement a custom 404 page in my .NET 5.0 for when the web app is in production. I have implemented the following in Startup.cs;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            } 
            else
            {
                app.UseStatusCodePagesWithRedirects("/Error/{0}");
            } 
            ...
}

Linking to a simple ErrorController

public class ErrorController : Controller
    {
        [Route("/Error/{statusCode}")]
        public IActionResult HttpStatusCodeHandler(int statusCode)
        {
            switch(statusCode)
            {
                case 404:
                    //ViewBag.ErrorMessage("Resource could not be found.");
                    break;
            }
            return View("Error");
        }
    }

and goes to Error.cshtml found in Shared.

This does nothing to remove the default Status Code: 404; Not Found page, but the page is accessible if I go to localhost/Error/404 directly through url.

This is how I remember implementing this with previous versions of .NET, but now I'm unsure if I'm missing something or if the new .NET 5.0 has a new requirement for implementing the custom 404 page.

Any help would be greatly appreciated.

Edit: launchSettings.json Profile:

"Proj_prod": {
            "commandName": "Project",
            "dotnetRunMessages": "true",
            "launchBrowser": true,
            "applicationUrl": "https://localhost:5001;http://localhost:5000",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Production"
            }
        }
Duwe answered 29/5, 2021 at 15:12 Comment(6)
i believe you're just running app in development mode. Nothing is wrong with the codeEcumenism
You can change the environment variable ASPNETCORE_ENVIRONMENT from Development to Production inside the Properties\LaunchSettings.json and test again. As Alexander Mokin said it is because you're testing int development environment.Kwangchow
@AlexanderMokin Sorry failed to mention that I already checked to ensure that "ASPNETCORE_ENVIRONMENT" is set to "Production". Edited the question to include the launchSettings profile details just in case.Duwe
setting ASPNETCORE_ENVIRONMENT to Production doesn't guarantee you're running the Proj_prod configuration. The default config is IISExpress. Put a breakpoint on the line app.UseStatusCodePagesWithRedirects("/Error/{0}"); and check if you're hitting it on startup.Ecumenism
@AlexanderMokin The breakpoint on app.UseStatusCodePagesWithRedirects is being hit on startup. Just in case, I set IISExpress to Production as well and it produces the same result as with Proj_prod.Duwe
You can try to rebuild a new project. For me, setting the environment of IIS Express to Production and using your code will work well.Vervain
D
4

Okay the actual code in question works as intended. A work partner added app.UseStatusCodePages(); far later down the Configure which I didn't notice.

(Yes, it took 14 days. I've finally went back to this and just noticed.)

Duwe answered 14/6, 2021 at 22:50 Comment(0)
U
0

First check if you have a correct route or if you are being redirected to /Error/404 and then You can redirect the user to the custom 404

 [Route("/Error/{statusCode}")]
    public IActionResult HttpStatusCodeHandler(int? statusCode)
    {
        switch(statusCode.Value)
        {
            case 404:
                //ViewBag.ErrorMessage("Resource could not be found.");
                //TempData["Message"] = "Resource could not be found."
                return RedirectToAction("404");
                break;
        }
        return View("Error");
    }

PS: you can also use app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}"); which would send the request parameter, not as a route

Ulland answered 30/5, 2021 at 15:46 Comment(1)
My issue is that when I input any junk url, I am not being redirected to /Error/_404_, it would simply remain in the junk url and output Status Code: 404; Not Found. I have tried the above implementation just in case but there was no change to my issue. app.UseStatusCodeWithRedirect / app.UseStatusCodePagesWithReExecute is being hit on startup.Duwe
H
0

I understand you run your project IIS Express. for that you could not find your custom error page as expected. You should use "ASPNETCORE_ENVIRONMENT": "Production" in your profile in launchsettings.json.and it resolves your issue. just change your code like below.


//clarify

  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"   //add this
      }
    },
    "Proj_prod": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Headed answered 31/5, 2021 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.