title: Why does my C# client, POSTing to my WCF REST service, return (400) Bad Request?
body: <p>I'm trying to send a POST request to a simple WCF service I wrote, but I keep getting a 400 Bad Request. I'm trying to send JSON data to the service. Can anyone spot what I'm doing wrong? :-)</p>
  
  <p>This is my service interface:</p>
  
  <pre><code>public interface Itestservice
  {
      [OperationContract]
      [WebInvoke(
          Method = "POST",
          UriTemplate = "/create",
          RequestFormat = WebMessageFormat.Json,
          ResponseFormat = WebMessageFormat.Json)]
      String Create(TestData testData);
  }
  </code></pre>
  
  <p>The implementation:</p>
  
  <pre><code>public class testservice: Itestservice
  {
      public String Create(TestData testData)
      {
          return "Hello, your test data is " + testData.SomeData;
      }
  }
  </code></pre>
  
  <p>The DataContract:</p>
  
  <pre><code>[DataContract]
  public class TestData
  {
      [DataMember]
      public String SomeData { get; set; }
  }
  </code></pre>
  
  <p>And finally my client code:</p>
  
  <pre><code>private static void TestCreatePost()
  {
      Console.WriteLine("testservice.svc/create POST:");
      Console.WriteLine("-----------------------");
  
      Uri address = new Uri("http://localhost:" + PORT + "/testweb/testservice.svc/create");
  
      // Create the web request  
      HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
  
      // Set type to POST  
      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      //request.ContentType = "text/x-json";
  
      // Create the data we want to send  
      string data = "{\"SomeData\":\"someTestData\"}";
  
      // Create a byte array of the data we want to send  
      byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
  
      // Set the content length in the request headers  
      request.ContentLength = byteData.Length;
  
      // Write data  
      using (Stream postStream = request.GetRequestStream())
      {
          postStream.Write(byteData, 0, byteData.Length);
      }
  
      // Get response  
      using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
      {
          // Get the response stream  
          StreamReader reader = new StreamReader(response.GetResponseStream());
  
          // Console application output  
          Console.WriteLine(reader.ReadToEnd());
      }
  
      Console.WriteLine();
      Console.WriteLine();
  }
  </code></pre>
  
  <p>Can anyone think of what I might be doing wrong? As you can see in the C# client I've tried both application/x-www-form-urlencoded and text/x-json for ContentType, thinking that might have something to do with it, but it doesn't seem to. I've tried a GET version of this same service and it works fine, and returns a JSON version of TestData with no problem. But for POST, well, I'm pretty stuck at the moment on this :-(</p>