How can we done Custom Error Page in MVC?

Category: C SharpHow can we done Custom Error Page in MVC?
Editor">Editor Staff asked 2 years ago

How can we done Custom Error Page in MVC?

1 Answers
Editor">Editor Staff answered 2 years ago

The HandleErrorAttribute allows you to use a custom page for this error. First you need to update your web.config file to allow your application to handle custom errors.

 

  1. <system.web>  
  2.     <customErrors mode=“On”>  
  3. </system.web>  

Then, your action method needs to be marked with the atttribute.

 

  1. [HandleError]  
  2. public class HomeController: Controller  
  3. {  
  4.     [HandleError]  
  5.     publicActionResultThrowException()  
  6.     {  
  7.         throw new ApplicationException();  
  8.     }  
  9. }  

By calling the ThrowException action, this would then redirect the user to the default error page. In our case though, we want to use a custom error page and redirect the user there instead.So, let’s create our new custom view page.
 
Most Asked ASP.NET MVC Interview Questions and Answers
 
Next, we simply need to update the HandleErrorAttribute on the action method.

 

  1. [HandleError]  
  2. public class HomeController: Controller   
  3. {  
  4.     [HandleError(View = “CustomErrorView”)]  
  5.     publicActionResultThrowException()   
  6.     {  
  7.         throw new ApplicationException();  
  8.     }  
  9. }