System.Runtime.Serialization.Serialization异常:应为命名空间中的元素
本文关键字:Serialization 命名空间 元素 Runtime 异常 System | 更新日期: 2023-09-27 17:58:24
出于某种原因,我觉得这个对post的调用设置不正确,这意味着我收到的消息是WCF中的方法没有在post中接收InventoryRequest对象?
var inventoryRequest = new InventoryRequest
{
memberID = "1",
Inventories = _inventories.ToArray()
};
//Act
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/Inventory");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
inventoryResponse = await client.PostAsJsonAsync("", inventoryRequest).Result.Content.ReadAsAsync<InventoryResponse>();
}
我在MSTest中收到此错误:
System.Runtime.Serialization.SerializationException: Error in line 1 position 70. Expecting element 'InventoryResponse' from namespace 'http://schemas.datacontract.org/2004/07/Responses'.. Encountered 'Element' with name
'Fault', namespace 'http://schemas.microsoft.com/ws/2005/05/envelope/none'.
at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlReader reader)
同样奇怪的是,它在谈论上面的xml阅读器。我指定json作为内容类型,那么它为什么要尝试使用xml进行解析呢?
旁注:当我在Fiddler中尝试对同一个uri执行POST并在Fiddler主体中指定InventoryRequest的json表示时,它工作得很好。。。并返回json
以这种方式尝试:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
inventoryResponse = await client.PostAsJsonAsync("Inventory", inventoryRequest).Result.Content.ReadAsAsync<InventoryResponse>();
}