HttpClient.ReadAsAsync <T> Returns an empty object when using [Serializable]

I work with Microsoft ASP.NET Web API client libraries (version 4.0.30506, since I have to work on the .NET Framework 4.0) to interact with the .NET web interface. I confirmed that the data was received in a fine. However, the object returned from the ReadAsAsync call remains uninhabited (not null). After digging on the Internet, I found this SO entry (see also answer):

HttpClient ReadAsAsync () response does not completely deserialize an object

It turns out that the objects that I send to the client via JSON are marked [Serializable], and that deleting this attribute makes everything work fine (which I confirmed with testing). However, these objects need the [Serializable] attribute for other scenarios where they are used in other applications, so simply removing the attribute is not really an option.

My code is shown below. Calls (not shown) to the Get method return an unreleased Customer object when the [Serializable] attribute is applied to the Customer object (as shown). When an attribute is removed, the returned Customer object is a populated property.

    [Serializable]
    public class Customer
    {
        public string Name { get; set; }
    }

    public class WebAPIClient
    {
        private readonly HttpClient _httpClient;

        public WebAPIClient(Uri baseAddress)
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = baseAddress:
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public Customer Get(int id)
        {
            string url = [code that builds url] + id.ToString();
            HttpResponseMessage response = _httpClient.GetAsync(url).Result;
            response.EnsureSuccessStatusCode();
            return response.Content.ReadAsAsync<Customer>().Result;
        }
    }

Can someone explain why I see this behavior and how I can get around it without removing the [Serializable] attribute from my data classes?

+4
1

- ...

public static class ApiUtil
{
    static HttpClient GetApiClient()
            {
                var client = new HttpClient();
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["apiUrl"]);
                return client;
            }

    public static async Task<Customer> GetCustomer(int id)
            {
                var client = GetApiClient();
                string query = "Customers(" + id + ")";
                var response = await client.GetAsync(query);
                return await response.Content.ReadAsAsync<Customer>();
            }
}

- async...

var customer = await ApiUtil.GetCustomer(1);

async , , - ...

var customerTask = ApiUtil.GetCustomer(1);
customerTask.Wait();
var customer = customerTask.Result;
-2

Source: https://habr.com/ru/post/1537966/


All Articles