ASP.NET Core MVC Custom Error Page Tutorial (C#.NET)

How to create a custom error page in asp.net core mvc using c#.net. This Step-by-step tutorial show custom page error handling in production app.
In today's article I will show you a simple tutorial with example how you can set or display the custom error page in you asp.net core mvc application. This will help you to understand the ASP.NET Core custom error handling and a completer detail about ASP.NET Core error handling tutorial. After completing this article, you will get clear understanding about ASP.NET Core custom error handling. 

So, for this article first we will create a new asp.net core mvc application. Here I have user asp.net core mvc 10 to demonstrate detail about error handling with ASP.NET Core MVC custom error page. So, for this article first we will create an asp.net core mvc application and add the below code in Program.cs file.  (If this configuration is not in your configuration file)

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // Production: route exceptions and status codes to /Error
    app.UseExceptionHandler("/Home/Error");
    app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
    app.UseHsts();
}
else
{
    app.UseExceptionHandler("/Home/Error");
} 
In above code as pe environment error page have been called. Now we will add a model class file named as  ErrorViewModel.cs in your model class file.
public class ErrorViewModel
{
    public string? RequestId { get; set; }
    public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    public int? StatusCode { get; set; }
    public string Message { get; set; } = "An error occurred while processing your request.";
    public string? Detailed { get; set; }
    public string? ResponsePath { get; set; }
    public bool IsDevelopment { get; set; }
} 
Here in above model class I have defined few properties.  this we are going to use in custom error page and in controller. Now add a controller class file and add the below code in it. Here for demo purpose i have added a httpget method and error action method. In this I have error action method code in this you can pass value to error.cshtml file present in shared folder as shown below.

Error .cshtml page

Now let's add the code to controller.
using CustomErrorPage.Models;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace CustomErrorPage.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            int val1 = 1;
            int val2 = 0;
            int result = val1 / val2; // This will throw a DivideByZeroException
            return View();
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            ErrorViewModel errorViewModel = new ErrorViewModel();
            int statusCode = HttpContext.Response.StatusCode;

            var env = HttpContext.RequestServices.GetService(typeof(IHostEnvironment)) as IHostEnvironment;
            errorViewModel.IsDevelopment = env?.IsDevelopment() ?? false;

            errorViewModel.RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
            errorViewModel.StatusCode = statusCode;

            if (statusCode != 0)
            {
                switch (statusCode)
                {
                    case 404:
                        errorViewModel.Message = "The resource you requested could not be found.";
                        break;
                    case 401:
                        errorViewModel.Message = "Unauthorized access.";
                        break;
                    case 403:
                        errorViewModel.Message = "You do not have permission to access this resource.";
                        break;
                    case 500:
                        errorViewModel.Message = "Inernal server Error.";
                        break;
                }

                
                if (errorViewModel.IsDevelopment)
                {
                    // When re-executed for a status code, you can get original path info (development only)
                    var statusFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
                    if (statusFeature != null)
                    {
                        errorViewModel.Detailed = $"OriginalPath: {statusFeature.OriginalPath}{statusFeature.OriginalQueryString}";
                    }
                    // When re-executed for a status code, you can get original path info (development only)
                    var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
                    if (exceptionFeature?.Error != null)
                    {
                        errorViewModel.Detailed = exceptionFeature.Error.ToString();
                    }
                    errorViewModel.ResponsePath= HttpContext.Request.Path;
                }
            }

            return View(errorViewModel);
        }
    }
}  
In above code I have taken two variable and used to throw exception by dividing the number. In next action method I have defined the error action method. This will execute whenever any exception will happen. 

In Error action method i have capture detail like error message to display, request code, error status code like 401, 403, 405, 505. If environment is development on that case technical error detail have been added in detail property. Now let's open the error.cshtml file and add the below code. 
@model ErrorViewModel
@{
    ViewData["Title"] = "Error";
}

<h2 class="text-danger">Error.</h2>
<h3 class="text-danger">@Model.Message</h3>

@if (Model.StatusCode != null)
{
    <h2>HTTP @Model.StatusCode</h2>
}

@if (Model.IsDevelopment && !string.IsNullOrEmpty(Model.Detailed))
{
    @if (Model.ShowRequestId)
    {
        <p>
            <strong>Request ID:</strong> <code>@Model.RequestId</code>
        </p>
        <p>
            <strong>Response Path: </strong><code>@Model.ResponsePath</code>
        </p>
    }
    <h2>Details (Development only)</h2>
    <pre>@Model.Detailed</pre>
} 
In this page you can display the detail as per your requirement.  In this i have added reference of view model class and display the property value as per requirement. You can customize the view of custom error page as pe your requirement.  Now let's run the code to check the output.

Error message

In above code I am getting error divide by zero, now let's press F5 to check the final output.

Custom Error Page
ASP.NET Core MVC Custom Error Page Tutorial (C#.NET).zip 2.14MB

Post a Comment