我是WCF的新手,但在阅读了有关StackOverflow的文章和几个问题之后,我们设法启动了一个自托管的RESTful服务。 我最终面临的问题是返回给操作契约的参数值为null。我意识到之前有几个问题,但我认为我已经处理了那里提出的所有设置,并没有解决问题。 我能够得到一个json响应,但它的json主体被发送到" POST"调用没有被反序列化到参数对象中。
下面是代码: -
[ServiceContract]
public interface IExchServer
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/init")]
DomainInfo init();
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/close")]
string close(DomainInfo connection); }
这是班级
[DataContract]
public class DomainInfo
{
[DataMember]
public string Domain { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public string password {get;set;}}
在我正在使用的其他客户端(PostMan)我已将标头设置为application / json。我尝试过以下有效载荷:
{"DomainInfo":{
"Domain": "domain.com",
"UserName": "admin@domain.com",
"password": "pass@123"}}
以及
{"Domain": "domain.com",
"UserName": "admin@domain.com",
"password": "pass@123"}
在第一个中,我得到以下WCF跟踪
Incoming HTTP request to URI 'http://localhost:9001/ExchServer/close' matched operation 'close'
Opening System.ServiceModel.InstanceContext/17818390
Opened System.ServiceModel.InstanceContext/17818390
A message was read
An unrecognized element was encountered in the XML during deserialization which was ignored.
而在第二个我得到
Incoming HTTP request to URI 'http://localhost:9001/ExchServer/close' matched operation 'close'.
Opening System.ServiceModel.InstanceContext/5923895
Opening System.ServiceModel.InstanceContext/5923895
A message was read
An unrecognized element was encountered in the XML during deserialization which was ignored
An unrecognized element was encountered in the XML during deserialization which was ignored
An unrecognized element was encountered in the XML during deserialization which was ignored
没有报告其他错误。在调试模式下启动VS时,我看到paremeter为null。请指导我,因为它似乎是一个非常基本的用法。 init()契约按预期工作,并返回一个json字符串。 提前致谢。
答案 0 :(得分:0)
这个答案解决了这个问题。
Sending JSON to WCF Rest Service - object is always null 问题是参数名称必须与json对象名称匹配。 所以正确的json是
{"connection":{
"Domain": "domain.com",
"UserName": "admin@domain.com",
"password": "pass@123"}}