2

I got a REST WCF Service running in .net 4 and I've tested the web service it is working and accepting HttpRequest I make to it. But I ran into a problem trying to access the HttpRequest body within the web service. I've tried sending random sizes of data appended on the HttpRequest using both Fiddler and my WinForm app and I can't seem to find any objects in runtime where I can find my request body is located. My initial instinct was to look in the HttpContext.Current.Request.InputStream but the length of that property is 0, so I tried looking in IncomingWebRequestContext that object doesn't even have a method nor properties to get the body of the HttpRequest.

So my question is, is there actually a way to access the HttpRequest request body in WCF?

PS: The data inside the request body is JSON strings and for response it would return the data inside response body as JSON string too.

4

2 回答 2

9

简单得多,这个关于WCF + REST 的答案:请求数据在哪里?工作正常。

此外,如果您的请求正文是可反序列化的,您可以只传递一个类。除非有一些错别字,否则应该可以:

public class Banana
{
    public string Colour;
    public int Size;
}

...

[WebInvoke(
    Method = "POST", 
    UriTemplate = "bananas", 
    ResponseFormat=WebMessageFormat.Json, 
    RequestFormat=WebMessageFormat.Json)]
string CreateBanana(Banana banana);

...

public string CreateBanana(Banana banana)
{
    return "It's a " + banana.Colour + " banana!";
}

使用此资源的数据进行 POST{"Colour": "blue", "Size": 5}应该返回"It's a blue banana!".

于 2011-05-26T11:45:22.173 回答
4

尝试((System.ServiceModel.Channels.BufferedMessageData)(((System.ServiceModel.Channels.BufferedMessage)((OperationContext.Current.RequestContext).RequestMessage)).MessageData)).Buffer

它有类型System.ArraySegment<byte>

或阅读WCF + REST:请求数据在哪里?

于 2010-06-16T01:41:55.690 回答