我如何判断 Request/Response 在 Application_Error 中是否可用?

How can I tell if Request/Response is available in Application_Error?

如果 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或使用 or changing IIS config.

综上所述;如何判断应用程序启动时是否发生错误?

您想检查它是否是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");
    }
}