How to create JSON post to api using C#

c#, httpwebrequest, json, post

Solution

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

Problem

I'm in the process of creating a C# console application which reads text from a text file, turns it into a JSON formatted string (held in a string variable), and needs to POST the JSON request to a web api. I'm using .NET Framework 4. My struggle is with creating the request and getting the response, using C#. What is the basic code that is necessary? Comments in the code would be helpful. What I've got so far is the below, but I'm not sure if I'm on the right track. ``` //POST JSON REQUEST TO API HttpWebRequest request = (HttpWebRequest)WebRequest.Create("POST URL GOES HERE?"); request.Method = "POST"; request.ContentType = "application/json"; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] bytes = encoding.GetBytes(jsonPOSTString); request.ContentLength = bytes.Length; using (Stream requestStream = request.GetRequestStream()) { // Send the data. requestStream.Write(bytes, 0, bytes.Length); } //RESPONSE HERE ```

Original source