我正在尝试将自动反序列化的列表或值数组发布到名为RejectModel的复杂对象.这在以 JSON格式接收数据时非常有效,但在发送XML数据时,自动序列化程序会使rejectList为NULL. 我尝试使用默认的
我尝试使用默认的Xml序列化程序而不是dataContract序列化程序.这给了我以下错误:
No MediaTypeFormatter is available to read an object of type ‘List’1’
from content with media type ‘application/xml’.
我尝试将列表更改为具有相同结果的数组.
我觉得我只是没有正确地命名我的XML包含元素.任何建议,将不胜感激.
发表声明.接受rejectModel列表.
public HttpResponseMessage Post(List<RejectModel> rejectionList) { if (rejectionList == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The request was empty, malformed, or did not include an array of values."); } else if (rejectionList.Rejections.Length == 0) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "An empty array was passed."); } }
拒绝模型,我想接受这些列表/数组
[DataContract] public class RejectModel : BaseModel { [Required] [DataMember(IsRequired = true)] public int LeadId { get; set; } [DataMember] public int? PropertyId { get; set; } [DataMember] public string PartnerPropertyId { get; set; } [DataMember] public string OriginalSource { get; set; } [DataMember] public DateTime OriginalReferralDate { get; set; } }
我的许多请求尝试之一.我为“rejectList”尝试了很多标签名称.我在请求标头中包含“Accept:application / xml”.
<?xml version="1.0" encoding="UTF-8"?> <rejectList> <RejectModel> <LeadId>10102085</LeadId> <PropertyId>60278</PropertyId> </RejectModel> </rejectList>从未失败.奋斗了两天,发一个问题,在30分钟内找到答案.
使用DataContractSerializer(WebAPI的默认xml序列化程序)时,必须在XML请求和对象的DataContract中包含命名空间.即使您正在接收List,也需要将xml集合命名为“ArrayOf …”.以下是我原始问题结构的示例:
[DataContract(Namespace = "http://blahblah.org/2013/Some.Namespace.You.Defined")] public class RejectList{ List<RejectModel> list{ get; set; } } <ArrayOfRejectModel xmlns="http://blahblah.org/2013/Some.Namespace.You.Defined"> <RejectModel> ... </RejectModel> <RejectModel> ... </RejectModel> </ArrayOfRejectModel>
但是,如果在DataContract修饰中包含空名称空间,则不必在XML请求中包含名称空间.
[DataContract(Namespace = "")] public class RejectList{ List<RejectModel> list{ get; set; } } <ArrayOfRejectModel> <RejectModel> ... </RejectModel> <RejectModel> ... </RejectModel> </ArrayOfRejectModel>
相关阅读:
Adjust MVC 4 WebApi XmlSerializer to lose the nameSpace
Remove namespace in XML from ASP.NET Web API
How to serialize xml into desired format in asp.net web api