简体   繁体   English

如何向/与RESTful WCF服务传递和使用JSON参数?

[英]How to pass and consume a JSON parameter to/with RESTful WCF service?

I am a beginner at RESTful services. 我是RESTful服务的初学者。

I need to create an interface where the client needs to pass up to 9 parameters. 我需要创建一个接口,客户端需要传递最多9个参数。

I would prefer to pass the parameters as a JSON object. 我宁愿将参数作为JSON对象传递。

For instance if my JSON is: 例如,如果我的JSON是:

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

And if I need to execute a server side method below in the end: 如果我需要在下面执行下面的服务器端方法:

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

Question(s): 问题(S):
How should I make the call from the client-side with the above JSON string? 我应该如何使用上面的JSON字符串从客户端进行调用? And how can I create a signature and implementation of the RESTful service method that 我如何创建RESTful服务方法的签名和实现

  • accepts this JSON, 接受这个JSON,
  • parses and deserializes it into Person object and 将它解析并反序列化为Person对象和
  • calls / returns the FindPerson method's return value back to client? 调用/将FindPerson方法的返回值返回给客户端?

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. 如果要创建WCF操作以接收该JSON输入,则需要定义映射到该输入的数据协定。 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 ). 有一些工具会自动执行此操作,包括我在http://jsontodatacontract.azurewebsites.net/上写的一些工具(有关此工具是如何在此博客文章中编写的更多详细信息)。 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). 由于JSON需要进入请求的主体,因此最自然的HTTP方法是POST ,因此您可以按如下方式定义操作:方法为“POST”,样式为“Bare”(这意味着您的JSON直接映射到参数)。 Notice that you can even omit the Method and BodyStyle properties, since "POST" and WebMessageBodyStyle.Bare are their default values, respectively). 请注意,您甚至可以省略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;
}

Now, at the method you have the input mapped to lookupPerson . 现在,在该方法中,您将输入映射到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. 可以在下面找到使用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));
    }
});

1-Add the WebGet attribute 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-Use NewtonSoft to serialize/deserialize your json into your object (note the above just takes in String), NewtonSoft is much faster than the MS serializer. 2 - 使用NewtonSoft将您的json序列化/反序列化为您的对象(注意上面只接受String),NewtonSoft比MS序列化器快得多。

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

3- your .svc file will contain Factory="System.ServiceModel.Activation.WebServiceHostFactory 3-你的.svc文件将包含Factory =“System.ServiceModel.Activation.WebServiceHostFactory

4- your web.config will contain 4-你的web.config将包含

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

...and... ...和...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM