Shawn Weisfeld

I find when I talk to myself nobody listens. - Shawn Weisfeld
posts - 352, comments - 144, trackbacks - 34

My Links

News

The views expressed in this blog are mine and mine alone, not that of my employer, Microsoft, or anyone else’s. No warrantee is given for the quality of any material on this site.

Archives

Post Categories

Wednesday, June 29, 2011

HTTP POST to RESTful WCF Service from a .NET Client

Playing with the WCF REST Template today (http://visualstudiogallery.msdn.microsoft.com/fbc7e5c1-a0d2-41bd-9d7b-e54c845394cd). Good Stuff.

When you create a new project with the template it gives you a service called “Service1” we are going to use this guy with 1 minor change. In the “Create” method set it to echo back the object that was passed to it.

[WebInvoke(UriTemplate = "", Method = "POST")]
public SampleItem Create(SampleItem instance)
{
    return instance;
}

Ok now lets get to the meat of it and write the client

WebClient client = new WebClient();
string uri = "http://localhost.:9309/Service1/";
string data = "<SampleItem xmlns=\"http://schemas.datacontract.org/2004/07/WcfRestService2\"><Id>2147483647</Id><StringValue>String content</StringValue></SampleItem>";
client.Headers.Add("Content-Type", "application/xml");
var response = client.UploadString(uri, "POST", data);
Console.WriteLine(response);
Console.ReadKey();

I got the contents of the data string by looking at the “help” provide by the service. You can see this if you append “help” to your services URL. In my case that was http://localhost.:9309/Service1/help”. Don’t forget to add the appropriate content type. Finally upload the string and capture the response. . . that is it!

BONUS: if you want to create the XML request without the “uber-string” try this on for size. . . .

//create the xml request document
XNamespace ns = "http://schemas.datacontract.org/2004/07/WcfRestService2";
XDocument doc = new XDocument(     new XElement(ns + "SampleItem",         new XElement(ns + "Id", "2147483647"),         new XElement(ns + "StringValue", "String content")     ));

posted @ Wednesday, June 29, 2011 5:31 PM | Feedback (0) |

Powered by: