8

我是 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 方法的返回值给客户端?
4

2 回答 2

14

If you want to create a WCF operation to receive that JSON input, you'll need to define a data contract which maps to that input. There are a few tools which do that automatically, including one which I wrote a while back at http://jsontodatacontract.azurewebsites.net/ (more details on how this tool was written at this blog post). The tool generated this class, which you can use:

// 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;
}

Next, you need to define an operation contract to receive that. Since the JSON needs to go in the body of the request, the most natural HTTP method to use is POST, so you can define the operation as below: the method being "POST" and the style being "Bare" (which means that your JSON maps directly to the parameter). Notice that you can even omit the Method and BodyStyle properties, since "POST" and WebMessageBodyStyle.Bare are their default values, respectively).

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

Now, at the method you have the input mapped to lookupPerson. How you will implement the logic of your method is up to you.

Update after comment

One example of calling the service using JavaScript (via jQuery) can be found below.

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));
    }
});
于 2012-12-17T21:31:28.047 回答
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 序列化/反序列化到您的对象中(注意上面只接受字符串),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>
于 2012-12-17T14:19:43.193 回答