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
: 257 At:- 6/13/2017 3:26:06 PM
asp.net C# MVC custom error






1 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>

that's it, you are done.

0
At:- 6/14/2017 4:24:23 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