asp.net-coreexception

Displaying an HTML error page in ASP.NET Core


I would like to display an HTML error page when I catch a certain exception in my ASP.NET Core project. The page is stored in the project's root and I'm having trouble finding what I need to use in order to show this page. in this case, the application is already running and I would like the exception to be handled by redirecting the URL to the internally contained HTML page.

How do I do this?


Solution

  • If you want to execute custom error page,you could use UseStatusCodePagesWithReExecute and UseExceptionHandler middleware like below:

    Controller:

    public class ErrorController : Controller
    {
        [Route("Error/{statusCode}")]
        public IActionResult StatusCodeError(int statusCode)
        {
            return Redirect("Index.html");  //Index.html located in wwwroot folder
        }
    }
    

    Startup.cs:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    
        app.UseStatusCodePagesWithReExecute("/Error/{0}");
        app.UseExceptionHandler("/Error/500");
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
       //...
    }