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

39,856

Solution 1

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

Solution 2

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>()
Share:
39,856

Related videos on Youtube

Aqdas
Author by

Aqdas

Software Engineer with diverse work experience, including programming, software development, continuous integration, continuous development, continuous testing and consulting. Extensive knowledge of software development specifically using scrum methodology for project management related activities. I have a very strong proficiency in several programming languages like C#, VB.Net, ASP.Net, AJAX, JavaScript, and AngularJS. I have used almost every data engine and the list includes SQL Server, Oracle, Crystal Reports, MongoDB, and MS Access. I have worked on many different business domains like Title Insurance, Computer telephony integration (CTI) for CISCO, E-commerce, Healthcare, Video on Demand for mobile apps and CRM. I am always dedicated to meet customer requirements with innovative solutions that maximize efficiency and exceed capability targets. I am always comfortable to discuss the technical issues and solutions with scientists, analysts as well as clients for successful project delivery.

Updated on July 09, 2022

Comments

  • Aqdas
    Aqdas almost 2 years

    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?

  • yaakov
    yaakov over 7 years
    Why not just use await result.Content.ReadAsAsync<User>()?
  • Robert
    Robert over 7 years
    @cordan that is a solution too, but it needs extra reference to System.Net.Http.Formatting
  • Seema As
    Seema As over 6 years
    Pass relative url in POSTAsync string Baseurl = GetBaseUrl(microService); string url = "/client-api/api/token";
  • garfbradaz
    garfbradaz over 6 years
    Shouldnt use 'using' either for HttpClient.
  • Raju Paladiya
    Raju Paladiya about 6 years
    @SeemaAs, Thank you very much !!, Your solution is working fine in my case. You saved my lot's of time.
  • benmccallum
    benmccallum over 4 years
    If you're using dotnet core, install Microsoft.AspNet.WebApi.Client/ and you'll be good to go with ReadAsAsync<T>().
  • Juan Ignacio Avendaño Huergo
    Juan Ignacio Avendaño Huergo over 3 years
    This should be accepted answer really... don't you think?