How to get object using Httpclient with response Ok in Web Api

Aqdas picture Aqdas · Aug 28, 2016 · Viewed 31.4k times · Source

my web api like

    public async Task<IHttpActionResult> RegisterUser(User user)
    {
        //User Implementation here

        return Ok(user);
    }

I am using HTTPClient to request web api as mentioned below.

var client = new HttpClient();
string json = JsonConvert.SerializeObject(model);
var result = await client.PostAsync( "api/users", new StringContent(json, Encoding.UTF8, "application/json"));

Where i can find user object in my result request which is implemented on client application?

Answer

Robert picture Robert · Aug 28, 2016

You can use (depands on what you need), and de-serialize it back to user object.

await result.Content.ReadAsByteArrayAsync();
//or
await result.Content.ReadAsStreamAsync();
//or
await result.Content.ReadAsStringAsync();

Fe, if your web api is returning JSON, you could use

var user = JsonConvert.DeserializeObject<User>( await result.Content.ReadAsStringAsync());

EDIT: as cordan pointed out, you can also add reference to System.Net.Http.Formatting and use:

await result.Content.ReadAsAsync<User>()