如何判断Application_Error中是否有Request / Response?

时间:2015-01-22 15:35:00

标签: asp.net asp.net-mvc

如果Application_Error由应用启动中的异常触发,即RouteConfigBundleConfig,您如何检查Request / Response是否可用?目前,对Response.Clear的调用会引发System.Web.HttpException其他信息Response is not available in this context

void Application_Error(object sender, EventArgs e)
{
    //Log error
    Log.Error(e);

    //Clear
    Response.Clear();
    Server.ClearError();

    //Redirect
    Response.Redirect("~/Error");
}

其他问题建议重写为不使用Response或使用HttpContext.Current.Response或更改IIS config

总结;如何判断应用程序启动时是否发生了错误?

1 个答案:

答案 0 :(得分:4)

您想检查它是否是 HttpException

protected void Application_Error(Object sender, EventArgs e)
{
    var exception = Server.GetLastError();

    // Log error
    LogException(exception);

    var httpException = exception as HttpException;
    if (httpException != null)
    {
        Response.Clear();
        Server.ClearError();
        Response.TrySkipIisCustomErrors = true;

        Response.Redirect("~/Error");
    }
}