gpt4 book ai didi

c# - 如何向 RESTful WCF 服务传递和使用 JSON 参数?

转载 作者:太空狗 更新时间:2023-10-29 18:18:43 25 4
gpt4 key购买 nike

我是 RESTful 服务的初学者。

我需要创建一个接口(interface),客户端需要在其中传递最多 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 方法的返回值给客户端?

最佳答案

如果您想要创建一个 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”,样式为“裸”(这意味着您的 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));
}
});

关于c# - 如何向 RESTful WCF 服务传递和使用 JSON 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com