ASP.NET Web API returns NULL for object when using XML

久未见 提交于 2020-02-25 05:39:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!