Tuesday 16 February 2021

Part 29: Handling Http Errors (404, 500 ..)

#5 minutes of reading

Application return 404 error status when requested resource not found. Example Mobile app which we discussed till now don’t have controller with name Test and if I provide controller name as Test, in this case application return with status 404. Run application and type below highlighted controller name in URL.
There are many ways to handle Http errors, let’s discuss one by one.

Http Errors with Use middleware:
Here will take help of User middleware to handle Http errors and create view to handle errors shown below.
Open Startup.cs file and modify code shown below.
Open Home controller and Add action method shown below. With below piece of code not only 404 but all types of Http Errors can handle.
HttpErrors view added in Home folder under views. I have created simple view to show status later you can update this view based on requirement and information you want to show.
Run application and type Test as controller in URL shown below.
  Asp.Net Core also provides mechanism to handles http errors with the help of middlewares.
1. UseStatusCodePages
2. UseStatusCodePagesWithRedirects
3. UseStatusCodePagesWithReExecute
UseStatusCodePages : This middleware shows basic view with http error 404.
Run application and check browser.
UseStatusCodePagesWithRedirects:
If you want more control over showing Http 404 error on your created custom view, UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute middleware is used. Update below code on Configure method of Startup.sc file.
Add below Action method in Home controller shown below.
Run application and check browser. Initial URL for below scenario is ‘https://localhost:44397/Error/404’ and after redirect URL gets change shown highlighted.
UseStatusCodePagesWithReExecute: This middleware avoids extra redirect performed.
Run application and check browser.

1 Comments:

At 16 February 2021 at 17:26 , Blogger Nihal Ahmed said...

Nice explained 👍

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home