WCF BodyStyle WrappedRequest对传入的JSON参数不起作用?

时间:2011-09-01 19:04:01

标签: wcf web-services json rest web

我一直致力于获取RESTful WCF服务,同时接受JSON作为参数并返回一些JSON。

这是我的服务:

    [OperationContract]
    [WebInvoke(
        Method="POST",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "Authenticate")]
    public AuthResponse Authenticate(AuthRequest data)
    {
        AuthResponse res = new AuthResponse();
        if (data != null)
        {
            Debug.WriteLine(data.TokenId);
            res.TokenId = new Guid(data.TokenId);
        }
        return res;
    }

当我通过{AuthRequest:{TokenId =“some guid”}}时,上面会将数据设置为空。

如果我将方法的BodyStyle设置为Bare,那么数据设置正确,但我必须从JSON中移除{AuthRequest}(我真的不想这样做)。有没有办法让WrappedRequests使用{AuthRequest:{TokenId =“some guid”}作为JSON?

感谢。

2 个答案:

答案 0 :(得分:20)

包装器的名称不是参数 type ,而是参数 name 。如果您将其作为{"data":{"TokenId":"some guid"}}发送,则应该有效。

或者,如果您想使用参数名称以外的名称,可以使用[MessageParameter]属性:

[OperationContract]
[WebInvoke(
    Method="POST",
    BodyStyle = WebMessageBodyStyle.WrappedRequest,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "Authenticate")]
public AuthResponse Authenticate([MessageParameter(Name = "AuthRequest")] AuthRequest data)

答案 1 :(得分:3)

这是一个迟到的回复,但我希望它对某人有帮助。

我还试图让JSON“POST”Web服务正常工作,但它的参数始终被设置为 null 。忘记尝试反序列化任何JSON数据,从来没有任何工作可做!

public string CreateNewSurvey(string JSONdata)
{
    if (JSONdata == null)
        return "JSON received: NULL, damn.";
    else
        return "You just sent me: " + JSONdata;
}

我的GET网络服务很棒,但是这个“POST”工作让我疯狂。

奇怪的是,我的解决方案是将参数类型从 string 更改为 Stream

public string CreateNewSurvey(Stream JSONdataStream)
{
    StreamReader reader = new StreamReader(JSONdataStream);
    string JSONdata = reader.ReadToEnd();

    //  Finally, I can add my JSON deserializer code in here!

    return JSONdata;
}

...在我的web.config中......

  [OperationContract(Name = "createNewSurvey")]
  [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "createNewSurvey")]
  string CreateNewSurvey(Stream JSONdata);   

有了这个,最后我的iPad应用程序可以调用我的WCF服务。我是一个快乐的人!希望这会有所帮助。