Thursday, July 3, 2008

How to read post request in WCF

Sometimes we have requirement in which we have to read data from request body / payload instead of its Querystring. Though it can be easily done in .NET 2.0 but it is hard to find in WCF. In this post, we'll see how to do it.

Here's the code to perform this


//Code Listing 1
public void MyPostHandler(Stream input){
StreamReader sr = new StreamReader(input);
string str = sr.ReadToEnd();
sr.Close();//str will contain the body payload of POST request
}

MyPostHandler method should be decorated with the WebInvoke attribute to handle Post requests. This is how it is done


//Code Listing 2
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "*")]
void MyPostHandler(Stream input);

So in the Code Listing 1 we see how raw request body was read into a string using the input Stream from which it arrived to the WCF service hosted in IIS

No comments: