C# 如何向/使用 RESTful WCF 服务传递和使用 JSON 参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13915765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass and consume a JSON parameter to/with RESTful WCF service?
提问by pencilCake
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):
How should I make the call from the client-side with the above JSON string?
And how can I create a signature and implementation of the RESTful service method that
问题:
我应该如何使用上述 JSON 字符串从客户端进行调用?以及如何创建 RESTful 服务方法的签名和实现
- accepts this JSON,
- parses and deserializes it into Person object and
- calls / returns the FindPerson method's return value back to client?
- 接受这个 JSON,
- 将其解析并反序列化为 Person 对象并
- 调用/将 FindPerson 方法的返回值返回给客户端?
采纳答案by carlosfigueira
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:
如果要创建 WCF 操作来接收该 JSON 输入,则需要定义映射到该输入的数据协定。有一些工具可以自动执行此操作,包括我不久前在http://jsontodatacontract.azurewebsites.net/ 上写的一个(有关如何在此博客文章中编写此工具的更多详细信息)。该工具生成了此类,您可以使用它:
// 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 Methodand BodyStyleproperties, since "POST"and WebMessageBodyStyle.Bareare their default values, respectively).
接下来,您需要定义一个操作合同来接收它。由于 JSON 需要进入请求正文,因此最自然的 HTTP 方法是使用POST,因此您可以定义如下操作:方法为“POST”,样式为“Bare”(这意味着您的 JSON直接映射到参数)。请注意,您甚至可以省略Method和BodyStyle属性,因为"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. How you will implement the logic of your method is up to you.
现在,在该方法中,您将输入映射到lookupPerson. 您将如何实现方法的逻辑取决于您。
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));
}
});
回答by lcryder
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 序列化/反序列化到你的对象中(注意上面只接受字符串),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>

