filmov
tv
Centralised 404 error handling in ASP NET Core
Показать описание
Text version of the video
Healthy diet is very important for both body and mind. We want to inspire you to cook and eat healthy. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking.
Slides
ASP.NET Core Text Articles & Slides
ASP.NET Core Tutorial
Angular, JavaScript, jQuery, Dot Net & SQL Playlists
UseStatusCodePages
UseStatusCodePagesWithRedirects
UseStatusCodePagesWithReExecute
Types of 404 errors
In ASP.NET Core there are 2 types of 404 errors that could happen
Type 1 : Resource with the specified ID does not exit. We discussed how to handle this type of 404 errors and provide a more meaningful and a more customised error view in Part 57 of ASP.NET core tutorial.
Type 2 : The provided URL does not match any route in our application. In this video, we will discuss how to handle this type of 404 error in a centralised way.
404 error example in ASP.NET Core
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc(routes =]
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
Default 404 error page in ASP.NET Core
Handling non-success http status codes
UseStatusCodePages
UseStatusCodePagesWithRedirects
UseStatusCodePagesWithReExecute
UseStatusCodePages Middleware
This is the least useful of the 3 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, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseStatusCodePages();
}
app.UseStaticFiles();
app.UseMvc(routes =]
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
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, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseStatusCodePagesWithRedirects("/Error/{0}");
}
app.UseStaticFiles();
app.UseMvc(routes =]
{
routes.MapRoute("default", "{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.
app.UseStatusCodePagesWithRedirects("/Error/{0}");
Комментарии