'HttpWebRequest.GetResponse() throwing multiple exceptions

I have this static class used for sending Http POST requests to my webserver via the HttpWebRequest libraries:

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;

namespace WebAPI
{
public static class HttpNetwork
{
    public delegate void CommandCallback(object obj);

    public static HttpWebResponse Send(IAPICommand command, CommandCallback callback = null)
    {
            try
            {
                //setup callback
                command.SetCallback(callback);

                string url = @command.GetRoute();

                HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
                httpRequest.Method = "POST";
                httpRequest.Accept = "application/json";
                httpRequest.ContentType = "application/json";
                httpRequest.KeepAlive = false;

                using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    string json = JsonConvert.SerializeObject(command, GetJsonSerializerSettings());
                    streamWriter.Write(json);
                }

                var response = (HttpWebResponse)httpRequest.GetResponse();
                command.HandleResponse(response);
                return response;
            }
            catch (Exception e)
            {
                WebLogger.LogWarning("Api Response error. Server down? " + e.Message);
            }

        return null;
    }

    private static JsonSerializerSettings GetJsonSerializerSettings()
    {
        return new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
            ObjectCreationHandling = ObjectCreationHandling.Replace
        };
    }
}
}

The first transaction works fine however the second transaction causes the following exception to be thrown when calling httpRequest.GetResponse():

System.AggregateException: One or more errors occurred. (The remote server returned an error: (500) Internal Server Error.) ---> System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponseFromData (System.Net.WebResponseStream stream, System.Threading.CancellationToken cancellationToken) [0x00146] in <b8d272a8be0e439da4052df4419466c7>:0 
at System.Net.HttpWebRequest.RunWithTimeoutWorker[T] (System.Threading.Tasks.Task`1[TResult] workerTask, System.Int32 timeout, System.Action abort, System.Func`1[TResult] aborted, System.Threading.CancellationTokenSource cts) [0x000f8] in <b8d272a8be0e439da4052df4419466c7>:0 
at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00020] in <b8d272a8be0e439da4052df4419466c7>:0 
at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <31c0f51ac5a24a22ba784db24f4ba023>:0 
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <31c0f51ac5a24a22ba784db24f4ba023>:0 
at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in <31c0f51ac5a24a22ba784db24f4ba023>:0 
at System.Threading.Tasks.Task`1[TResult].get_Result () [0x0000f] in <31c0f51ac5a24a22ba784db24f4ba023>:0 
at System.Net.HttpWebRequest.GetResponse () [0x00006] in <b8d272a8be0e439da4052df4419466c7>:0 
---> (Inner Exception #0) System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponseFromData (System.Net.WebResponseStream stream, System.Threading.CancellationToken cancellationToken) [0x00146] in <b8d272a8be0e439da4052df4419466c7>:0 
at System.Net.HttpWebRequest.RunWithTimeoutWorker[T] (System.Threading.Tasks.Task`1[TResult] workerTask, System.Int32 timeout, System.Action abort, System.Func`1[TResult] aborted, System.Threading.CancellationTokenSource cts) [0x000f8] in <b8d272a8be0e439da4052df4419466c7>:0 
at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00020] in <b8d272a8be0e439da4052df4419466c7>:0 
at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <31c0f51ac5a24a22ba784db24f4ba023>:0 <---

Any ideas as to what I've done wrong? Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source