amiry jd
amiry jd

Reputation: 27585

Show custom error page in MVC 3 doesn't work!

I set custom error enable in Web.config:

<customErrors mode="On"/>

and, in Application_Start, put these:

protected void Application_Error(object sender, EventArgs e) {

    var ex = Server.GetLastError().GetBaseException();

    var routeData = new RouteData();

    if (ex.GetType() == typeof(HttpException)) {
        var httpException = (HttpException)ex;
        var code = httpException.GetHttpCode();
        routeData.Values.Add("status", code);
    } else {
        routeData.Values.Add("status", -1);
    }

    routeData.Values.Add("action", "Index");
    routeData.Values.Add("controller", "Error");
    routeData.Values.Add("error", ex);

    IController errorController = new Kavand.Web.Controllers.ErrorController();
    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}

also I create an error controller like this:

public class ErrorController : Kavand.Web.Mvc.Kontroller
{
    public ActionResult  Index(int status, Exception error) {
        Response.StatusCode = status;
        HttpStatusCode statuscode = (HttpStatusCode)status;
        return View(statuscode);
    }
}

but, when an error occurred, the yellow-page shown, instead of my custom view! can everybody help me please?! Thanks a lot, regards

Upvotes: 1

Views: 1253

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Don't forget to clear the error in Application_Error after fetching it:

protected void Application_Error(object sender, EventArgs e)
{
    var ex = Server.GetLastError().GetBaseException();
    Server.ClearError(); // <-- that's what you are missing
    var routeData = new RouteData();
    ...
}

Also it is important to remove the HandleErrorAttribute global attribute which is added in the RegisterGlobalFilters static method in Global.asax as you no longer need it.

You may also find the following answer useful.

Upvotes: 3

Related Questions