Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize-deserialize object using HTTP GetAsync method?

After I upgraded the framework of web app from 4.0 to 4.6 I found that there is no more ReadAsAsync() method in HTTP protocol library, instead of ReadAsAsync() there is GetAsync(). I need to serialize my custom object using GetAsync().

The code using ReadAsAsync():

CustomResponse customResponse = client.ReadAsAsync("api/xxx", new StringContent(new JavaScriptSerializer().Serialize(request), Encoding.UTF8, "application/json")).Result; 

Another example based on ReadAsAsync()

CustomResponse customResponse = await Response.Content.ReadAsAsync<CustomResponse>(); 

How to achieve same goal using GetAsync() method ?

like image 382
Dmitry Kazakov Avatar asked Feb 11 '26 00:02

Dmitry Kazakov


1 Answers

You can use it this way: (you might want to run it on another thread to avoid waiting for response)

using (HttpClient client = new HttpClient())
{
    using (HttpResponseMessage response = await client.GetAsync(page))
    {
        using (HttpContent content = response.Content)
        {
            string contentString = await content.ReadAsStringAsync();
var myParsedObject = (MyObject)(new JavaScriptSerializer()).Deserialize(contentString ,typeof(MyObject));
        }

    }
}
like image 105
TTomer Avatar answered Feb 12 '26 15:02

TTomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!