Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON payload for HttpClient in C#?

How to pass in a JSON payload for consuming a REST service.

Here is what I am trying:

var requestUrl = "http://example.org";

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualifiedHeaderValue("application/json"));
    var result = client.Post(requestUrl);

    var content = result.Content.ReadAsString();
    dynamic value = JsonValue.Parse(content);

    string msg = String.Format("{0} {1}", value.SomeTest, value.AnotherTest);

    return msg;
}

How do I pass something like this as a parameter to the request?:

{"SomeProp1":"abc","AnotherProp1":"123","NextProp2":"zyx"}
like image 479
TruMan1 Avatar asked Nov 20 '11 05:11

TruMan1


1 Answers

I got the answer from here: POSTing JsonObject With HttpClient From Web API

httpClient.Post(
    myJsonString,
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));
like image 146
TruMan1 Avatar answered Oct 01 '22 03:10

TruMan1