Search code examples
c#asp.net.netroutesasp.net-core-mvc

How do I make my program route to a custom 404 error page? (C#/.NET)


I have a project that uses the Entity Framework. I am trying to make it route to a custom Error (including the _Layout.cshtml file) page whenever something goes wrong but it keeps returning the standard 404 error page.

This is my Program.cs page

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PlacementPlanner_v1.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<PlacementPlanner_v1Context>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("PlacementPlanner_v1Context") ?? throw new InvalidOperationException("Connection string 'PlacementPlanner_v1Context' not found.")));

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.

if (app.Environment.IsDevelopment()) // if not in dev mode
{
    app.UseDeveloperExceptionPage();

} else
{
    app.UseStatusCodePagesWithRedirects("/Error/{0}"); //point to error page
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

// gonna add in custom routing here and see if it works for aboutUs page. This is a conventional route
app.MapControllerRoute(
    name: "aboutUs",
    pattern: "aboutUs/{action}",
    defaults: new { controller = "AboutUs", action = "Index"}); // this only routes to the AboutUsController.Index
app.MapControllerRoute( 
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");


app.Run();

This is my Error Controller:

using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

public class ErrorController : Controller
{
    public IActionResult Error(int? statusCode)
    {
        if (statusCode.HasValue)
        {
            if (statusCode == 404)
            {
                return View("NotFound");
            } else
            {
                return View("GenError");
            }
            
        }
        return View();
    }
}

And finally I have 2 custom razor pages, NotFound, and GenError. Both are in found in the Views -> Error folder

I have tried moving things around a bit but it just wont seem to work. Any help would be appreciated. Thank you.


Solution

  • Below is a work demo, you can refer to it, hope it can help you.

    In Program.cs modify the code like:

    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    ...
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    app.UseStatusCodePagesWithRedirects("/Error/{0}"); //point to error page
    app.Run();
    

    Then in the ErrorController add the Route like:

    public class ErrorController : Controller
    {
     
        [Route("Error/{statusCode}")]
        public IActionResult Error(int? statusCode)
        {
            if (statusCode.HasValue)
            {
                if (statusCode == 404)
                {
                    return View("NotFound");
                }
                else
                {
                    return View("GenError");
                }
    
            }
            return View();
        }
    }
    

    result:

    enter image description here