在MVC 3中显示自定义错误页面不起作用!

时间:2011-06-27 19:38:20

标签: asp.net-mvc-3 error-handling custom-error-pages

我在Web.config中设置了自定义错误:

<customErrors mode="On"/>

并在Application_Start中输入以下内容:

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));
}

我也创建了一个这样的错误控制器:

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

但是,当发生错误时,会显示黄页,而不是我的自定义视图!请大家帮帮我吗?! 非常感谢,问候

1 个答案:

答案 0 :(得分:3)

取出后,请不要忘记清除Application_Error中的错误:

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();
    ...
}

同样重要的是删除HandleErrorAttributeRegisterGlobalFilters静态方法中添加的Global.asax全局属性,因为您不再需要它。

您可能还会发现following answer有用。