问题
I've tried to follow the instructions I found, but still it does not work.
I have following class
public class TodoItem
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
public TodoItem() { }
}
My server has following POST Method
public IHttpActionResult Post([FromBody]TodoItem item)
{
if (item != null)
{
TodoRepository.Current.Add(item);
return Ok(item);
}
return BadRequest("Object is null");
}
In my WebApiConfig.cs I have added following line
config.Formatters.XmlFormatter.UseXmlSerializer = true;
On the client side I am using HttpClient as follows:
var postTask = client.PostAsXmlAsync<TodoItem>("", item);
My Post method on server receives null for the item object.
回答1:
Thanks, solved the problem with the help of Nilesh Thakkar
I have added following extension method
public static class HttpExtensions
{
public static Task<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, string requestUri, T value)
{
return client.PostAsync(requestUri, value,
new XmlMediaTypeFormatter { UseXmlSerializer = true });
}
}
The call from HttpClient now looks
var postTask = client.PostAsXmlWithSerializerAsync<TodoItem>("", item);
回答2:
I believe this answer could be also useful. PostAsXmlAsync uses XmlMediaTypeFormatter which internally uses DataContractSerializer, which creates XML from DataContract in alphabetical order(XmlSerializer - in defined order). So, using "Order Parameter" in the DataMemberAttribute class could help with PostAsXmlAsync-deserialization-issue:
[DataMember(Order = index)]
来源:https://stackoverflow.com/questions/40741343/asp-net-web-api-returns-null-for-object-when-using-xml