Centralised 404 error handling in ASP NET Core

preview_player
Показать описание

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}");
Рекомендации по теме
Комментарии
Автор

Your channel has consistently helped me in my educational and professional life. Thank you for the sustained quality!

go_fuck_yourself
Автор

Life saver for a needed quick fix. Appreciate it.

ben
Автор

Thanks a lot man!!!!.... The best .net core videos.

pollo
Автор

Sir, can we add hyperlink in form if we have already given tag helper in form tag. Also how we can get value of textbox on controller? Not on form submit but on clicking hyperlink

nishthakapur
Автор

my guy you saved my life here with this one ha

WeBreatheOxy
Автор

I just keep getting this "Hello World!" from Startup.cs last method. app.Run(async (context) => {await World"); No 404 messages, no NotFound views, nothing, just Hello World! I am using ASP NET Core 3.1.1 and VS 16.4.3. Enviroment variable has no effect, any error gives me Hello World!. Kind of funny aigh. Edit; When i type url Error/404 it goes to that page, otherwise not. I have tried changes mentioned in previous comments too. Edit1; I got it; had to disable the last "Hello World" method. The request went down there through the pipeline without returning to if else block. Great tutorial Mr.Kudvenkat Sir.

TommiLipponen
Автор

Thanks for great video tutorial but i have one problem. This works as good as shown when we use other route than we have in our app. What if we have custom route with parameters to navigate and we state other parameters than it should be instead of showing error same page is viewed?
My question:
How to handle when the URL provided matches one of your routes, but the controller name OR PARAMETERS provided isn't correct.?
I have setup my custom routes in start up as:

endpoints.MapControllerRoute(
name: "singleproduct",
pattern: "productlist/{catlinkUrl}/{subcatlinkUrl?}/{sku}",
defaults: new { controller = "Product", action = "SingleProduct" }
);
endpoints.MapRazorPages();


This projects my url how it should be.. But if someone types diffrently in exact same route syntax then how to show notfound page error without redirecting

gyan_ko_sagar
Автор

Hey guys need some help! I have followed these tutorials from the beginning and everything worked fine up til now. Any issues I had turned out to be typos. I have followed the suggestions in these comments but it does not change anything for me. If I navigate to /foo/bar I get a 500 error. What can I do?

williamneel
Автор

Why we created new Razor View called NotFound in Shared folder insead to create new folder Error (because we created ErrorController)? As we have Home folder for HomeController...

MegaJorgovan
Автор

@kudvenkat Hello sir, I have been following this tutorial from the very beginning and I absolutely loved each and every video Thank you soo much for helping. But I have faced an issue, So when ever i change my environment to production all the image cards alignment has changed in the Index page can you help me sort this problem?

nithinreddykotta
Автор

After doing everything as you did, instead of getting Error/404 view, I got:


This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500

I changed environment back to Development and got:

InvalidOperationException: The layout view '_NonAdminLayout' could not be located. The following locations were searched:




So I copied _Layout.cshtml and renamed it to _NonAdminLayout.cshtml and it worked in both Development and Production environment.

Is there another way to solve this (without _NonAdminLayout.cshtml) and does anyone know why it didn't work without _NonAdminLayout.cshtml?

PS I'm working on Ubuntu machine and using Visual Studio Code which uses it's own launch.json instead of launchSettings.json and from what I've seen on one of the first tutorials in this series, VSC uses Kestrel server instead of Visual Studio's IIS Express.

p_andrej_
Автор

Hello,
For me everything works good, except for the fact that the code from the previous video doesn't work, when I change only the ID to 99 for example I get:
404 Not Found Error :
Employee with Id = 0 cannot be found
How do I fix this so that the ID showed will be 99 again.

excessiveaholecritic
Автор

Those who still have 500 error, Move NotFound.cshtml to Error Folder(create) in Views. Also add @section scripts to NotFound.cshtml, [optional {if required add @model int -- for statusCode}] ...launchSettings.json : if you run in IIS Express profile keep -->profiles: "IIS Express" "ASPNETCORE_ENVIRONMENT": "Production" or if you run in EmployeeManagement --> "ASPNETCORE_ENVIRONMENT": "Production"..and use

nimaljvalath
Автор

Fucking thank you i was searching for this.

miguelcastillo
Автор

Hmm this work only under IIS express not with full pledged IIS :(

darkogele
Автор

I did the same as the video but why did i get error 500?

afossible
Автор

If anyone else got the 500 error, I was getting the same thing. I realized I had created the NotFound view in the Views folder and not the Views/Shared folder. Once I fixed that, the 500 error went away.

bigalfantasy
Автор

I still get these error from using your code:
CS0103 The name 'photo' does not exist in the current context EmployeeManagement 155 Active

Error CS0103 The name 'photo' does not exist in the current context EmployeeManagement 159 Active

josephregallis
Автор

Why do we need a new ErrorController? We could just use the HomeController!

hossammetwally
Автор

Make sure to add /(slash) before the error page extension, this will prevent 500 error:


deepankarjoshi