1

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

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

4

1 回答 1

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

此外,删除静态方法中HandleErrorAttribute添加的全局属性也很重要,因为您不再需要它。RegisterGlobalFiltersGlobal.asax

您可能还会发现以下答案很有用。

于 2011-06-27T19:48:50.457 回答