pen*_*ake 8 .net c# wcf json wcf-rest
我是RESTful服务的初学者.
我需要创建一个接口,客户端需要传递最多9个参数.
我宁愿将参数作为JSON对象传递.
例如,如果我的JSON是:
'{
"age":100,
"name":"foo",
"messages":["msg 1","msg 2","msg 3"],
"favoriteColor" : "blue",
"petName" : "Godzilla",
"IQ" : "QuiteLow"
}'
Run Code Online (Sandbox Code Playgroud)
如果我需要在下面执行下面的服务器端方法:
public Person FindPerson(Peron lookUpPerson)
{
Person found = null;
// Implementation that finds the Person and sets 'found'
return found;
}
Run Code Online (Sandbox Code Playgroud)
问题:
如何使用上述JSON字符串从客户端进行调用?我如何创建RESTful服务方法的签名和实现
car*_*ira 13
如果要创建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;
}
Run Code Online (Sandbox Code Playgroud)
接下来,您需要定义一个操作合同来接收它.由于JSON需要进入请求的主体POST,因此使用最自然的HTTP方法,因此您可以按如下方式定义操作:方法为"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;
}
Run Code Online (Sandbox Code Playgroud)
现在,在您将输入映射到的方法中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));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31227 次 |
| 最近记录: |