Search code examples
httpcontext

Getting "object reference not set to an instance" in HttpContext.Current.Application


I'm hardly to figure out how to solve this.. I want to catch the error when the server is turn off and redirect the page to Maintenance.aspx. But it's getting error at HttpContext.Current.Application["ErrorCode"].ToString();.Please help me how to solve this...

Many thanks.

try{
// method here
}
 catch (Exception ex)
       {
            Panel1.Visible = true;
            string statuscode = HttpContext.Current.Application["ErrorCode"].ToString(); //Getting error here!
            if (statuscode != null || statuscode != string.Empty)
            {
                if (statuscode == "500")
                {
                    lblDetailMsg.Text = "<b>Error Page- <b> " + HttpContext.Current.Application["ErrorPage"].ToString() + " <br /> <b>Error Message-</b> The Requested Page was not found.";
                    Response.Redirect("Maintenance.aspx");
                }
            }

        }

Solution

  • If I understand your code right, then the error must be due to .toString() method.

    Try this

    string statuscode = Convert.ToString(HttpContext.Current.Application["ErrorCode"]); // added Convert.Tostring()
        if (statuscode != null || statuscode != string.Empty)
        {
            if (statuscode == "500")
            {
                 lblDetailMsg.Text = "<b>Error Page- <b> " + Convert.ToString(HttpContext.Current.Application["ErrorPage"]) + " <br /> <b>Error Message-</b> The Requested Page was not found.";
                 Response.Redirect("Maintenance.aspx");
            }
        }
    

    Convert.ToString() handles null, while ToString() doesn't.

    Here it seems that HttpContext.Current.Application["ErrorCode"] does not contain value for "Error Code", so it giving null value.