首页 > 解决方案 > How to read and deserialize IEnumerable of objects with httpclient

问题描述

I have a problem with reading and deserializing the HTTP response from my simple web API that supposes to return IEnumerable of ContactDto object. In contentReader.Read() line I'm getting an error as:

"Data at the root level is invalid. Line 1, position 1."

Controller get code:

    [HttpGet]
    // GET api/<controller>
    public IEnumerable<ContactDto> Get()
    {
        return new List<ContactDto>()
        {
            new ContactDto()
            {
                DateOfBirth = DateTime.Today,
                FirstName = "tmp",
                LastName = "tmp"
            }
        };
    }

Model code:

public class ContactDto
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime DateOfBirth { get; set; }
}

Reading and parsing with HttpClient:

public IEnumerable<ContactDto> Read()
{
        var serializer = new XmlSerializer(typeof(ContactDto));

        var client =new HttpClient();

        var stream = client.GetStreamAsync(_feedUrl).Result;

            using (var streamReader = new StreamReader(stream))
            {
                using (var contentReader = new XmlTextReader(streamReader))
                {
                    while (contentReader.Read())
                    {
                        var innerEventXml = contentReader.ReadAsString();
                        using (var stringReader = new StringReader(innerEventXml))
                        {
                            yield return (ContactDto) serializer.Deserialize(stringReader);
                        }
                    }
                }
            }
}

标签: c#asp.net

解决方案


Returning a list of objects in your Get action results in a JSON result when calling it, not a XML result.

You can deserialize it using Newtonsoft.Json for example:

string result = client.GetStringAsync().Result;
return JsonConvert.Deserialize<List<ContactDto>>(result);

Althought I would suggest you to use await for the async methods.


推荐阅读