9

I'm attempting to send a json "styled" string via HttpResponseMessage.

I have created to following method below in hope of sending the response message successfully.

class Foo
{
    /// <summary>
    /// Vendors
    /// </summary>
    public enum Vendor
    {
        [Description("https://someSite.com")]
        FOO = 0x001
    }

    /// <summary>
    /// Send a POST response
    /// </summary>
    /// <param name="vendor"></param>
    /// <param name="data"></param>
    public static async void SendResponseAsync(Vendor vendor, string data)
    {
        Task task = Task.Run(async () =>
        {
            using (var httpClient = new HttpClient())
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, vendor.EnumDescriptionToString()))
            {
                var json = Newtonsoft.Json.JsonConvert.DeserializeObject(data);
                httpRequestMessage.Content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
                var result = await httpClient.SendAsync(httpRequestMessage);
                Console.WriteLine(result.ReasonPhrase);
            }
        });
        await task;
    }
}

And I'm calling it with the following;

static void Main()
{
    string jsonText = "{\"apikey\": \"someAPIkey\",\"type\": \"ItemRegistered\",   \"order\": \"999999\",   \"item\": \"99999\",    \"datetime\": \"2018-10-12 01:27:11 GMT\"}";
    Foo.SendResponseAsync(Foo.Vendor.FOO, jsonText);
    Console.ReadKey();
}

The error I'm receiving is 400 now you could say that that is my issue right there, and indeed you are correct, however,

I'm wondering why is it that when I use PostMan that I receive an error that says the order number is not recognized? in json format,

So I understand that the order number is not correct, however, why is it not showing in my console app? Is my method for POSTING correct?

traveler3468
  • 1,557
  • 2
  • 15
  • 28

1 Answers1

8

You should pass serialized json representation into StringContent. You json variable is of type object instead, and when you call ToString() it gives you something like class type. If your data is already serialized json, just pass that.

Or, if you have an object, pass it like this:

var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
Maxim Zabolotskikh
  • 3,091
  • 20
  • 21