Aqdas Aqdas - 3 months ago 12
ASP.NET (C#) Question

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

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

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());
Comments