In this article I will explain how to solve the following error (exception) occurring inside the GetResponse method of HttpWebRequest class in C# and VB.Net.
An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code. Additional information: The remote server returned an error: (500) Internal Server Error.
 
 
Exception
In following code snippet, the response is being received using the GetResponse method of HttpWebRequest class.
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
    using (Stream stream = httpResponse.GetResponseStream())
    {
        string json = (new StreamReader(stream)).ReadToEnd();
    }
}
 
But it raises the following exception:-
An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code. Additional information: The remote server returned an error: (500) Internal Server Error.
 
HttpWebRequest GetResponse: The remote server returned an error: (500) Internal Server Error
 
 
Reason
This exception could be occurring due to any internal error related to database, runtime error, etc. But problem is the above exception does not give any information why the exception is occurring.
 
 
Solution
Though this is not a solution, it will help us find the real cause of the exception.
The code snippet is now wrapped into a Try-Catch block and the WebException is caught in the Catch block.
The exception details are extracted from the WebException object using StreamReader class.
try
{
    using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
    {
        using (Stream stream = httpResponse.GetResponseStream())
        {
            string json = (new StreamReader(stream)).ReadToEnd();
            gvCustomers.DataSource = (new JavaScriptSerializer()).Deserialize<List<Customer>>(json);
            gvCustomers.DataBind();
        }
    }
}
catch (WebException ex)
{
    string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
 
Now when the code is again executed, the details of the exception occurring are now available in the message variable.
HttpWebRequest GetResponse: The remote server returned an error: (500) Internal Server Error