How to HTTP Post in .NET and handle the 500 errors

How to HTTP Post in .NET and handle the 500 errors

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

I have been posting to a service and getting the “500 Internal Server Error,” which doesn’t tell you much. I did some research to get at 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 you think or if you have a better approach.