If you google you will find a lot of posts that will tell you how to HTTP post (some call it HTML post) in .NET. However, they all fail, or at least the ones I found, to tell you how to handle the returned 500 errors and retrieve the message behind it.

I have been posting to a service and getting the “500 Internal Server Error” which doesn’t tell much! I had done some research to get the real error behind it. Here is my code snippet in C#:

public static string Post(string url, string postData) {

byte[] buffer = Encoding.UTF8.GetBytes(postData);
int bufferLength = buffer.Length;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bufferLength;

string result;

using (Stream requestStream = request.GetRequestStream()) {
    requestStream.Write(buffer, 0, bufferLength);

    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            using (Stream responseStream = response.GetResponseStream()) {
                using (StreamReader readStream = 
                       new StreamReader(responseStream, Encoding.UTF8)) {
                    result = readStream.ReadToEnd();
                }
            }
        }
    }
    catch (WebException wEx) {
        using (Stream errorResponseStream = wEx.Response.GetResponseStream()) {
            using (StreamReader errorReadStream = 
                   new StreamReader(errorResponseStream, Encoding.UTF8)) {
                result = errorReadStream.ReadToEnd();
            }
        }
    }
}

return result;
}

I have tested the code and it is working, please let me know what do you think or if you have a better approach.