Search code examples
c#wcfpostwebinvoke

WCF WebInvoke POST message body


[OperationContract]
[WebInvoke(UriTemplate = "s={s}", Method = "POST")]
string EchoWithPost(string s);

I'm trying to consume this method (WCF service) using a WebRequest:

WebRequest request1 = WebRequest.Create("http://MyIP/Host");
request1.Method = "POST";
request1.ContentType = "application/x-www-form-urlencoded";
string postData1 = "s=TestString";

I don't want to pass the data (s=TestString) in the url, what I'm trying to do is passing the data in the message body.


Solution

  • First you need to change your service contract like this:

    [OperationContract]
    [WebInvoke(UriTemplate = "EchoWithPost", Method = "POST")]
    string EchoWithPost(string s);
    

    Notice how the UriTemplate is no longer expecting any variable value in the URL.

    To invoke such an operation from a client:

    // Set up request
    string postData = @"""Hello World!""";
    HttpWebRequest request = 
         (HttpWebRequest)WebRequest.Create("http://MyIP/Host/EchoWithPost");
    request.Method = "POST";
    request.ContentType = "text/json";
    byte[] dataBytes = new ASCIIEncoding().GetBytes(postData);
    request.ContentLength = dataBytes.Length;
    using (Stream requestStream = request.GetRequestStream())
    {
         requestStream.Write(dataBytes, 0, dataBytes.Length);
    }
    
    // Get and parse response
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string responseString = string.Empty;
    using (var responseStream = new StreamReader(response.GetResponseStream()))
    {
         //responseData currently will be in XML format 
         //<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello World!</string>
         var responseData = responseStream.ReadToEnd();
         responseString = System.Xml.Linq.XDocument.Parse(responseData).Root.Value;
    }
    
    // display response - Hello World!
    Console.WriteLine(responseString);
    Console.ReadKey();