WCF POST test harness

Writing RESTful JSON services with WCF is fun; in fact I do it for a living.  One thing that every developer finds useful is a small program for testing calls, trying new ideas etc so here is my C# test harness for handling POST requests.

private static void PostThis()
    {
      const string baseUrl = "http://127.0.0.1";
      const string port = ":81/";
      const string serviceEndpoint = "Rest.svc/";
      const string serviceAction = "Client/[email protected]/";

      //Create URL to POST request data too.
      string url = baseUrl + port + 
                       serviceEndpoint + serviceAction;
      Console.WriteLine("Making POST request to: " + url);
      Uri address = new Uri(url);

      //Create webRequest  
      HttpWebRequest request = WebRequest.Create(address) 
                                           as HttpWebRequest;

      //the Method property of the request to POST  
      request.Method = "POST";
      //Set the ContentType to json
      //our service is expecting WebMessageFormat.Json
      request.ContentType = "application/json; charset=utf-8";

      //define the parameters
      string data = "{\"password\":\"S3cretP@ssw0rd\"}";

      //Create a byte array from your parameters
      byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

      //Set the content length in the request headers
      //this may require back end service alterations
      request.ContentLength = byteData.Length;

      //Make the request by streaming the data
      using (Stream dataStream = request.GetRequestStream())
      {
        dataStream.Write(byteData, 0, byteData.Length);
        dataStream.Close();
      }

      try
      {
        //Receive the response  
        HttpWebResponse response = request.GetResponse() 
                                          as HttpWebResponse;
        
        //Get the response stream  
        if (response != null)
        {
          StreamReader reader = new 
                                StreamReader(response.GetResponseStream());

          //Write output to the console
          Console.WriteLine();
          Console.WriteLine("Response: ");
          Console.WriteLine(reader.ReadToEnd());

          //Final cleanup
          reader.Close();
          response.Close();
        } 
      }
      catch (Exception ex)
      {
        //Display exceptions
        Console.WriteLine(ex.ToString());
      }

      Console.WriteLine("Press enter to quit");
      Console.ReadLine();
    }

Many examples exist on the web for making POST webRequests but most of them specify the incorrect ContentType for JSON WCF services, usually you will find this:

request.ContentType = “application/x-www-form-urlencoded”;

Instead for JSON services you need to use:

request.ContentType = “application/json; charset=utf-8”;

If you use the incorrect ContentType you will get the following http 400 error

“The remote server returned an error: (400) Bad Request”

Simply change the service endpoints constants at the top of the code to your details and test away. I like to run the code in a simple console application. I may do a separate post on the WCF service configuration if I get time.

Also, if you’re looking for a nifty tool to test JSON response data look no further than these guys http://jsonformatter.curiousconcept.com/

2 thoughts on “WCF POST test harness

  1. but how to use the ContentType whith “application/x-www-form-urlencoded”, and the post data will be
    password=S3cretP@ssw0rd
    Thanks:)

Leave a Reply

Your email address will not be published. Required fields are marked *