Can't Pass JSON Post Data to WCF REST Service

2019-05-17 21:42发布

问题:

I'm trying to invoke a WCF rest service as shown below:

[WebInvoke(UriTemplate = "Login", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public string Process(string AuthenticationInfo)
{

I'm trying to invoke it using the following below in Fiddler 2:

User-Agent: Fiddler
Host: localhost
content-type: application/json;charset=utf-8
content-length: 0
data: {"AuthenticationInfo": "data"}

I have a breakpoint in the method, and it does hit the breakpoint, but the value for AuthenticationInfo is always null, and not "data".

What am I doing wrong?

Thanks.

回答1:

The default "body style" of the [WebInvoke] attribute is "Bare", which means that the input (in your case, "data") must be sent "as is". What you're sending is a wrapped version of the input (i.e., wrapped in an object whose key is the parameter name.

There are two ways you can make this work: either change the WebInvoke declaration to include the BodyStyle parameter:

[WebInvoke(
    UriTemplate = "Login", 
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public string Process(string AuthenticationInfo)   

Or you can change the request to send the parameter "bare":

POST .../Login HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Type: application/json;charset=utf-8
Content-Length: 6

"data"


回答2:

Are you setting the HTTP method to POST in Fiddler? By default WCF REST operations are POST, if you want to do gets you need to set Method="GET" on the WebInvoke attribute. BTW, in your case I don't think a GET makes sense since you're sending in data, so just make sure you're using POST in Fiddler.



回答3:

You send Content-Length as 0, but it should be the length of your POST-Data.