Introduction :
In this tutorial we are going to discuss How to handle 404 errors in ASP.NET Core MVC, When a web page is not found and a 404 error is returned by the application, ASP.NET Core MVC presents only a generic browser error page.
To performing this article you should have installed visual studio 2019 installed on your system, if you don’t have then installed it from here download Visual Studio 2019 here.
How to handle 404 errors in ASP.NET Core MVC
The following is code in Configure() method of Startup class in Startup.cs file. As you might already know, this Configure() method configures the HTTP request processing pipeline for our asp.net core application.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
Default 404 error page in ASP.NET Core
If we do not have anything configured in this http request processing pipeline to handle 404 errors. So if we navigate invalid URL like https://localhost:44377/home/employee, we see the following default 404 error page. This is because the URL /home/employee does not match any routes in our application.
handle 404 errors in ASP.NET Core MVC
To handle non-success http status codes such as 404 for example, we could use the following 3 built-in asp.net core middleware components.
UseStatusCodePages
UseStatusCodePagesWithRedirects
UseStatusCodePagesWithReExecute
UseStatusCodePages Middleware
This is the least useful status code middleware components. For this reason, we rarely use it in a real world production application. To use it in an application and see what it can do, plug it into the http processing pipeline as shown below.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseStatusCodePages(); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
With UseStatusCodePages Middleware configured, if we navigate to
https://localhost:44377/home/employee, it returns the following simple text response.
UseStatusCodePagesWithRedirects Middleware
In a production quality application we want to intercept these non-success http status codes and return a custom error view. To achieve this, we can either use UseStatusCodePagesWithRedirects middleware or UseStatusCodePagesWithReExecute middleware.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseStatusCodePagesWithRedirects("/Error/{0}"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
With the following line in place, if there is a 404 error, the user is redirected to /Error/404. The placeholder {0}, in “/Error/{0}” will automatically receive the http status code.
In HomeController add ActionMethod HttpStatusCodeHandler
public class HomeController : Controller { [Route("Error/{statusCode}")] public IActionResult HttpStatusCodeHandler(int statusCode) { switch (statusCode) { case 404: ViewBag.ErrorMessage = "404, Requested resource was not found"; break; } return View("PageNotFound"); } }
PageNotFound View :
At this point, if we navigate to https://localhost/Home/employee we see the following custom 404 error view PageNotFound.cshtml as expected.
To use UseStatusCodePagesWithReExecute middleware instead of UseStatusCodePagesWithRedirects middleware
we need to replace UseStatusCodePagesWithRedirects(“/Error/{0}”) middleware with UseStatusCodePagesWithReExecute(“/Error/{0}”)
When we use UseStatusCodePagesWithReExecute middleware we see below error massage with same page URL
Difference between UseStatusCodePagesWithRedirects vs UseStatusCodePagesWithReExecute middleware
UseStatusCodePagesWithRedirects : By using this middleware if error comes then it redirect to error page
UseStatusCodePagesWithReExecute : By using this middleware if error comes then error page content will display but not redirect to error page as shown in above two screenshot difference.
Also Learn More Tutorial :
- ASP.Net Core: Form Submit (Post) with Example
- File(Image) Upload in ASP.NET Core MVC with Example
- .Net Core: Read Connection String from AppSettings.json file
- CRUD Operation Using Asp.Net Core Mvc with Repository Pattern
- Display Data in GridView(Grid) Using ASP.Net Core MVC
- Asp.Net Core: DbContext In EntityFramework core
- Difference between AddSingleton vs AddScoped vs AddTransient in asp.net core
- Difference between .NET Core and .NET Framework
- Difference between TempData keep() And Peek() in Asp.Net MVC
- Asp.Net Image Upload in 3-Tier Architecture and store in sql database
- ViewImports in ASP.NET Core MVC