I would like to show custom errors in my Asp.NET MVC C# application, how can i achieve it?
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.
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."
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly