【问题标题】:WCF BodyStyle WrappedRequest doesn't work for incoming JSON param?WCF BodyStyle WrappedRequest 不适用于传入的 JSON 参数?
【发布时间】:2011-09-01 19:04:01
【问题描述】:

我一直致力于让 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"} } 时,上面将设置 data 为空。

如果我将方法的 BodyStyle 设置为 Bare,则 data 设置正确,但我必须从 JSON 中删除 { AuthRequest }(我真的不想这样做)。有什么方法可以让 WrappedRequests 与 { AuthRequest: { TokenId = "some guid"} 作为 JSON 一起工作?

谢谢。

【问题讨论】:

    标签: wcf web-services json rest web


    【解决方案1】:

    包装器的名字不是参数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)
    

    【讨论】:

    • 完美答案 :) 不知道它的参数名称不是类型,并且消息参数名称选项很好知道!
    • 拯救了我的一天!几乎相同的问题,但由于关键字不同,我没有找到您的问题:stackoverflow.com/questions/39048349/…
    【解决方案2】:

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

    我也试图让 JSON“POST”网络服务工作,但它的参数总是设置为 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 服务了。我是一个快乐的人!希望这会有所帮助。

    【讨论】:

    • 假设你想使用 POSTMAN 调用它,SoapUI 你会怎么做?
    • @ Mike Gledhill ...在我的web.config中...? :( IService.cs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2013-06-11
    相关资源
    最近更新 更多