title: Send JSON via POST in C# and Receive the JSON returned?
body: <p>This is my first time ever using JSON as well as <code>System.Net</code> and the <code>WebRequest</code> in any of my applications. My application is supposed to send a JSON payload, similar to the one below to an authentication server:</p>
  
  <pre><code>{
    "agent": {                             
      "name": "Agent Name",                
      "version": 1                                                          
    },
    "username": "Username",                                   
    "password": "User Password",
    "token": "xxxxxx"
  }
  </code></pre>
  
  <p>To create this payload, I used the <code>JSON.NET</code> library. How would I send this data to the authentication server and receive its JSON response back? Here is what I have seen in some examples, but no JSON content:</p>
  
  <pre><code>var http = (HttpWebRequest)WebRequest.Create(new Uri(baseUrl));
  http.Accept = "application/json";
  http.ContentType = "application/json";
  http.Method = "POST";
  
  string parsedContent = "Parsed JSON Content needs to go here";
  ASCIIEncoding encoding = new ASCIIEncoding();
  Byte[] bytes = encoding.GetBytes(parsedContent);
  
  Stream newStream = http.GetRequestStream();
  newStream.Write(bytes, 0, bytes.Length);
  newStream.Close();
  
  var response = http.GetResponse();
  
  var stream = response.GetResponseStream();
  var sr = new StreamReader(stream);
  var content = sr.ReadToEnd();
  </code></pre>
  
  <p>However, this seems to be a lot of code compaired to using other languages I have used in the past. Am I doing this correctly? And how would I get the JSON response back so I can parse it?</p>
  
  <p>Thanks, Elite.</p>
  
  <p><strong>Updated Code</strong></p>
  
  <pre><code>// Send the POST Request to the Authentication Server
  // Error Here
  string json = await Task.Run(() =&gt; JsonConvert.SerializeObject(createLoginPayload(usernameTextBox.Text, password)));
  var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
  using (var httpClient = new HttpClient())
  {
      // Error here
      var httpResponse = await httpClient.PostAsync("URL HERE", httpContent);
      if (httpResponse.Content != null)
      {
          // Error Here
          var responseContent = await httpResponse.Content.ReadAsStringAsync();
      }
  }
  </code></pre>