我有一个 RESTful WCF 服务,其方法声明如下:
[OperationContract(Name = "IncrementAge")]
[WebInvoke(UriTemplate = "/", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
Person IncrementAge(Person p);
实现如下:
public Person IncrementAge(Person p)
{
p.age++;
return p;
}
因此它采用 Person 复杂类型,将 age 属性递增 1,然后使用 JSON 序列化将其吐回。我可以像这样向服务发送 POST 消息来测试它:
POST http://localhost:3602/RestService.svc/ HTTP/1.1
Host: localhost:3602
User-Agent: Fiddler
Content-Type: application/json
Content-Length: 51
{"age":25,"firstName":"Hejhaj","surName":"Csuhaj"}
这行得通。如果我想要这样的方法怎么办?
Person IncrementAge(Person p, int amount);
所以它会有多个参数。我应该如何构建 POST 消息才能使其正常工作?这可能吗?
谢谢
最佳答案
您应该使消息正文样式包装,以便您可以在 POST 请求正文中接受多个参数。
您的方法签名将是:
[OperationContract(Name = "IncrementAge")]
[WebInvoke(UriTemplate = "/", Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
Person IncrementAge(Person p, int amount);
请求的正文将如下所示:
{"p": {"age":25,"firstName":"Hejhaj","surName":"Csuhaj"}, "amount": 1}
外部 JSON 对象是匿名包装器。
关于.net - 如何使用多个参数调用 RESTful WCF 服务方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4597220/