3

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 ?

1 Answer 1

4

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));
        }

    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

I need to serialize my custom object using GetAsync(). Your example use HttpResponseMessage, but I need to use CustomResponse object.
Why do you need to use a CustomResponse, exactly? This is how I create a Http request to an API and then just use my favourite de-serializer on the contentString - I'm pretty sure it's a "standard way" of doing it. What's different with using aCustomResponse?
In my app I use custom objects and I want to get the response and serialize it. I would like to have just few lines like in the provided examples.
@DmitryKazakov This is exactly what de/serializers are for - the remote app (usually a WebApp/API etc.), serializes a custom object at one end, and sends the serialized string. Then, the other (your own/local app) can de-serialize this string into the same type of custom object... This is a few lines of code. I use this exact (nearly) method day-in-day-out to get responses from Web Servers, and parse out objects. Again, I don't see how using a CustomResponse would benefit you differently?
I have the app built already. I had to upgrade framework version to add some functionality, but I do not want to refactor most of code (moreover it is not possible because few libraries are compiled and there is no source code). I just want to use GetAsync() in the same way like it was with ReadAsAsync() and serialization to keep the app working with compiled dlls.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.