检查HttpContext.Current对象中的空值

时间:2014-02-27 21:06:46

标签: c# asp.net httpcontext

我们遇到奇怪的情况,导致Http.Current对象(例如.Response.Request)出现异常。 NullReferecne是个例外。我的印象是HTTPContext在正常情况下不能为null。但是,在我们的案例中,它应该如何处理这种类型的异常?我们已经在Global.asax.cs中处理HTTPException,并使用ErrorSeverity作为本地类的Fatal。我已经修改了检查空值的代码,但如果真的遇到这种情况我就不知道了 - 请参阅下面的代码:

protected void Application_Error(object sender, EventArgs e)
    {
        try
        {
            Exception exception = Server.GetLastError();
            HttpException httpException = exception as HttpException;
            if (httpException != null)
            {
                if (httpException.GetHttpCode() == 404)
                {
                    return;
                }
            }
            string errMessage = "Running Application_Error. An unhandled error occured in the application.";
            errMessage = errMessage + "Error message = " + exception.Message;

            //This is the IF-ELSE I've added but it just doesn't "feel right"
            if (HttpContext.Current.Request != null || HttpContext.Current.Response != null)
            {
                StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Fatal);
            }
            else
            {
                StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Info);
            }

            exception = exception.InnerException;
            while (exception != null)
            {
                StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Fatal);
                exception = exception.InnerException;
            }

            QSession session = QSession.GetInstance();
            bool mobileIndicator = session != null ? session.Packet.QPolicy.IsMobileApplication : false; 
            if (mobileIndicator)
            {
                    LogAndRedirectTechDiff("MobileTechnicalDifficulties.htm", session != null);
            }
            else
            {
                //This is the IF-ELSE I've added but it just doesn't "feel right"                   
                if (HttpContext.Current.Request != null || HttpContext.Current.Response != null)
                {
                    LogAndRedirectTechDiff("TechnicalDifficulties.htm", session != null);
                }
                else
                {
                    LogAndRedirectTechDiff("UnsupportedBrowser.htm", session != null);
                }
            }

        }
        catch (Exception ex)
        {
            EventLog.WriteEntry("FQ",
                                "Global.asax.cs Application_Error method caused an exception. This is the error message :" +
                                ex.ToString(), EventLogEntryType.Error);
        }
    }

0 个答案:

没有答案