【问题标题】:How to pass and consume a JSON parameter to/with RESTful WCF service?如何向/使用 RESTful WCF 服务传递和使用 JSON 参数?
【发布时间】:2012-12-04 15:26:49
【问题描述】:

我是 RESTful 服务的初学者。

我需要创建一个接口,客户端需要传递最多 9 个参数。

我希望将参数作为 JSON 对象传递。

例如,如果我的 JSON 是:

'{
    "age":100,
    "name":"foo",
    "messages":["msg 1","msg 2","msg 3"],
    "favoriteColor" : "blue",
    "petName" : "Godzilla",
    "IQ" : "QuiteLow"
}'

如果我最后需要执行下面的服务器端方法:

public Person FindPerson(Peron lookUpPerson)
{
Person found = null;
// Implementation that finds the Person and sets 'found'
return found;
}

问题:
我应该如何使用上面的 JSON 字符串从客户端进行调用? 以及如何创建 RESTful 服务方法的签名和实现

  • 接受这个 JSON,
  • 将其解析并反序列化为 Person 对象并
  • 调用/返回 FindPerson 方法的返回值给客户端?

【问题讨论】:

标签: c# .net json wcf wcf-rest


【解决方案1】:

1-添加WebGet属性

<OperationContract()> _
        <WebGet(UriTemplate:="YourFunc?inpt={inpt}", BodyStyle:=WebMessageBodyStyle.Wrapped,
                RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Xml)> _
        Public Function YourFunch(inpt As String) As String

2-使用NewtonSoft将你的json序列化/反序列化到你的对象中(注意上面只接受String),NewtonSoft比MS序列化器快得多。

使用NewtonSoft进行序列化http://json.codeplex.com/

3- 您的 .svc 文件将包含 Factory="System.ServiceModel.Activation.WebServiceHostFactory

4- 你的 web.config 将包含

     <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>

...和...

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

【讨论】:

  • 如果要将 JSON 输入传递给 WCF 服务,则不应使用 [WebGet] - 输入应在请求正文中传递,因此不应使用 GET。它应该改用[WebInvoke]
【解决方案2】:

如果您想创建一个 WCF 操作来接收该 JSON 输入,您需要定义一个映射到该输入的数据协定。有一些工具可以自动执行此操作,包括我不久前在http://jsontodatacontract.azurewebsites.net/ 写的一个(有关此工具如何编写的更多详细信息,请参见this blog post)。该工具生成了这个类,您可以使用它:

// Type created for JSON at <<root>>
[System.Runtime.Serialization.DataContractAttribute()]
public partial class Person
{

    [System.Runtime.Serialization.DataMemberAttribute()]
    public int age;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string name;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string[] messages;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string favoriteColor;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string petName;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string IQ;
}

接下来,您需要定义一个操作合同来接收它。由于 JSON 需要放在请求的正文中,所以最自然的 HTTP 方法是POST,因此您可以将操作定义为:方法为“POST”,样式为“Bare”(这意味着您的 JSON 直接映射到参数)。请注意,您甚至可以省略 MethodBodyStyle 属性,因为 "POST"WebMessageBodyStyle.Bare 分别是它们的默认值。

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public Person FindPerson(Peron lookUpPerson)
{
    Person found = null;
    // Implementation that finds the Person and sets 'found'
    return found;
}

现在,在方法中,您将输入映射到lookupPerson。如何实现方法的逻辑取决于您。

评论后更新

下面是使用 JavaScript(通过 jQuery)调用服务的一个示例。

var input = '{
    "age":100,
    "name":"foo",
    "messages":["msg 1","msg 2","msg 3"],
    "favoriteColor" : "blue",
    "petName" : "Godzilla",
    "IQ" : "QuiteLow"
}';
var endpointAddress = "http://your.server.com/app/service.svc";
var url = endpointAddress + "/FindPerson";
$.ajax({
    type: 'POST',
    url: url,
    contentType: 'application/json',
    data: input,
    success: function(result) {
        alert(JSON.stringify(result));
    }
});

【讨论】:

  • 非常有用的答案 carlosfigueira! (能否也添加 Javascript 调用,使其大致涵盖所有部分)谢谢!
  • 我已经问过如何用 JavaScript 内置函数替换这个 jquery ajax 调用,仅使用 :)(如果有兴趣,请参阅我的最后一个问题 :))
  • msdn.microsoft.com/en-us/library/vstudio/… 的示例显示了一种使用 XMLHttpRequest 对象的方法。
  • 如果Bare 导致错误,WebMessageBodyStyle.WrappedRequest 可能对您有用。
猜你喜欢
  • 2015-06-03
  • 2012-07-03
  • 1970-01-01
  • 2014-03-04
  • 2015-05-13
  • 2017-07-10
  • 2011-01-02
  • 1970-01-01
  • 2011-10-10
相关资源
最近更新 更多