title: Why is my HttpWebRequest POST method to my WebAPI server failing?
body: <p>I've successfully received data from my WebAPI project ("GET"), but my attempt to Post is not working. Here is the relevant server/WebAPI code:</p>
  
  <pre><code>public Department Add(Department item)
  {
      if (item == null)
      {
          throw new ArgumentNullException("item");
      }
      departments.Add(item);
      return item; 
  }
  </code></pre>
  
  <p>...which fails on the "departments.Add(item);" line, when this code from the client is invoked:</p>
  
  <pre><code>const string uri = "http://localhost:48614/api/departments";
  var dept = new Department();
  dept.Id = 8;
  dept.AccountId = "99";
  dept.DeptName = "Something exceedingly funky";
  
  var webRequest = (HttpWebRequest)WebRequest.Create(uri);
  webRequest.Method = "POST";
  var deptSerialized = JsonConvert.SerializeObject(dept); // &lt;-- This is JSON.NET; it works (deptSerialized has the JSONized versiono of the Department object created above)
  using (StreamWriter sw = new StreamWriter(webRequest.GetRequestStream()))
  {
      sw.Write(deptSerialized);
  }
  HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;
  using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
  {
      if (httpWebResponse.StatusCode != HttpStatusCode.OK)
      {
          string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode);
          throw new ApplicationException(message);
      }  
      MessageBox.Show(sr.ReadToEnd());
  }
  </code></pre>
  
  <p>...which fails on the "HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;" line.</p>
  
  <p>The err msg on the server is that departments is null; deptSerialized is being populated with the JSON "record" so...what is missing here?</p>
  
  <h2>UPDATE</h2>
  
  <p>Specifying the ContentType did, indeed, solve the dilemma. Also, the StatusCode is "Created", making the code above throw an exception, so I changed it to:</p>
  
  <pre><code>using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
  {
      MessageBox.Show(String.Format("StatusCode == {0}", httpWebResponse.StatusCode));
      MessageBox.Show(sr.ReadToEnd());
  }
  </code></pre>
  
  <p>...which shows "StatusCode == Created" followed by the JSON "record" (array member? term.?) I created.</p>