我有一个WCF(启用了ajax)的Web服务,并且具有以下方法,该方法接受名为TypeRequest的对象。
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/XML/GetTypes",
BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
XElement XMLGetTypes(TypeRequest obj)
{
//do something
}
TypeRequest对象定义为;
[DataContract(Namespace = "")]
public class TypeRequest
{
[Required]
[DataMember]
public long Id{ get; set; }
[Required]
[DataMember]
public Account Account { get; set; }
}
然后我的孩子帐户课程如下;
[DataContract(Namespace = "")]
public class Account
{
/// <summary>
/// Email address
/// </summary>
[DataMember]
[Required]
[StringLength(175)]
public string Email { get; set; }
/// <summary>
/// Plain text password
/// </summary>
[DataMember]
[Required]
[StringLength(16, MinimumLength = 8)]
public string Password { get; set; }
}
我遇到的问题是,如果我通过以下示例Xml进行调用
<TypeRequest>
<Id>1</Id>
<Account>
<Email>myemail@domain.com</Email>
<Password>12345</Password>
</Account>
</TypeRequest>
到方法XMLGetTypes(TypeRequest obj),我可以查看obj和Id有正确的值,但是Account对象是null
为什么会这样,我做错了什么,因为我似乎无法弄明白。我是否需要提供更多信息才能获得帮助?
根据我之前的信息,我添加了一种接受JSON请求的方法,例如
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/JSON/GetTypes",
BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
string JSONGetTypes(TypeRequest obj)
{
//do something
}
使用JSON调用
{
"TypeRequest": {
"Id": "1",
"Account": {
"Email": "myemail@domain.com",
"Password": "12345"
}
}
}
我可以查看TypeRequest obj,并可以查看已发布的所有正确数据。因此,为什么Xml帖子不起作用?!?
答案 0 :(得分:0)
尝试将xml更改为此?
<TypeRequest>
<Id>1</Id>
<Account>
<Email>myemail@domain.com</Email>
<Password>12345</Password>
</TypeRequest>
答案 1 :(得分:0)
添加
[XmlSerializerFormat]到我的方法解决了这个问题。例如
[OperationContract]
[XmlSerializerFormat]
[WebInvoke(Method = "POST", UriTemplate = "/XML/GetTypes",
BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
XElement XMLGetTypes(TypeRequest obj)
{
//do something
}