Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 444
Aqdas Avatar asked Aug 28 '16 09:08

Aqdas


People also ask

How do you pass header values in web API using HttpClient?

var token = "MyToken"; client. DefaultRequestHeaders. Authorization = new AuthenticationHeaderValue(tokenType, token); //... other code removed for brevity.

Which method will be used from HttpClient class for fetching the data from cloud API?

The method simply invokes the get() method of HttpClient to send GET requests to the REST API server.


2 Answers

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>()
like image 115
Robert Avatar answered Oct 13 '22 07:10

Robert


string Baseurl = GetBaseUrl(microService);
string url = "/client-api/api/token";

using (HttpClient client = new HttpClient())`enter code here`
{
    client.BaseAddress = new Uri(Baseurl);
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

    List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();

    keyValues.Add(new KeyValuePair<string, string>("client_id", "5196810"));
    keyValues.Add(new KeyValuePair<string, string>("grant_type", "password"));
    keyValues.Add(new KeyValuePair<string, string>("username", "[email protected]"));
    keyValues.Add(new KeyValuePair<string, string>("password", "Sonata@123"));
    keyValues.Add(new KeyValuePair<string, string>("platform", "FRPWeb"));


    HttpContent content = new FormUrlEncodedContent(keyValues);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    content.Headers.ContentType.CharSet = "UTF-8";

    var result = client.PostAsync(url, content).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
}
like image 25
Seema As Avatar answered Oct 13 '22 07:10

Seema As