how to show custom errors in C# MVC


I would like to show custom errors in my Asp.NET MVC C# application, how can i achieve it?


Asked by:- Vipin
1
: 3932 At:- 6/13/2017 3:26:06 PM
asp.net C# MVC custom error







2 Answers
profileImage Answered by:- vikas_jk

Hello vipin, in order to implement custom error page, first you need to add these lines in your web.config file

<!--Add this within <system.web> tag-->
<customErrors mode="On" defaultRedirect="~/CustomError" >
  <error statusCode="404" redirect="~/CustomError/NotFound" />
</customErrors> 

as you can see we have made customErrors mode  'on' now,  second thing which you need to do id create Controller(CustomError) and NotFound action method in it

public class CustomErrorController : Controller
{
    public ActionResult Index()
    {
        return View("Error");
    }

    public ActionResult NotFound()
    {
        Response.StatusCode = 200;
        return View("NotFound");
    }

    public ActionResult InternalServer()
    {
        Response.StatusCode = 200;
        return View("InternalServer");
    }
}

Now this will redirect to CustomError page but it will show you Error URL in it, so to remove it use, this instead

<!--Turn off custom errors-->

<customErrors mode="Off" />

<!--Then in system.webServer-->

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" path="/NotFound.html" responseMode="File" />  
</httpErrors>

For detailed article, check Custom Error pages in ASP.NET MVC

that's it, you are done.

1
At:- 6/14/2017 4:24:23 AM


profileImage Answered by:- neena

Above solution works as needed, but you also need to get rid of

 filters.Add(new HandleErrorAttribute());

In FilterConfig.cs

Otherwise, you might error "The view 'Error' or its master was not found or no view engine supports the searched location."

0
At:- 6/25/2021 11:40:49 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use