Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Request Body in a WCF RESTful Service

Tags:

rest

c#

http

wcf

How do I access the HTTP POST request body in a WCF REST service?

Here is the service definition:

[ServiceContract]
public interface ITestService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "EntryPoint")]
    MyData GetData();
}

Here is the implementation:

public MyData GetData()
{
    return new MyData();
}

I though of using the following code to access the HTTP request:

IncomingWebRequestContext context = WebOperationContext.Current.IncomingRequest;

But the IncomingWebRequestContext only gives access to the headers, not the body.

Thanks.

like image 425
urini Avatar asked Aug 17 '09 12:08

urini


3 Answers

Best way i think doesn't involve WebOperationContext

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "EntryPoint", BodyStyle = WebMessageBodyStyle.Bare)]
MyData GetData(System.IO.Stream pStream);
like image 50
kasthor Avatar answered Oct 22 '22 17:10

kasthor


Use

OperationContext.Current.RequestContext.RequestMessage

like image 9
SajithK Avatar answered Oct 22 '22 18:10

SajithK


Sorry for the late answer but I thought I would add what works with UriTemplate parameters to get the request body.

[ServiceContract]
public class Service
{        
    [OperationContract]
    [WebInvoke(UriTemplate = "{param0}/{param1}", Method = "POST")]
    public Stream TestPost(string param0, string param1)
    {

        string body = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());

        return ...;
    }
}

body is assigned a string from the raw bytes of the message body.

like image 8
Gerard Sexton Avatar answered Oct 22 '22 17:10

Gerard Sexton