Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to ReadAsAsync method in HttpContent

I am using Microsoft.AspNet.WebApi.Client to consume rest services in my ASP.MVC 5 project. I am following the this tutorial to make use of HttpClient. The code is not compiling since ReadAsAsync method is no longer available in HttpContent. After digging a bit I came to know that it is an extension method defined in System.Net.Http.Formatting.dll. I found a nuget package for the same dll here but the package is deprecated and I am not able to install it. I also trid to search that dll in Program Files folder according to this post but I could not get it. Any ideas how to make ReadAsAsync work? Any help greatly appreiciated. Thanks.

like image 783
Tejas Sutar Avatar asked Sep 15 '26 21:09

Tejas Sutar


1 Answers

What do you need to do is to add new reference System.Net.HttpClient; and System.Net.HttpClient.Formating;.

This is my sample codes in HttpClient:

The following codes is use to get a certificate from saba using HttpClient.

using System.Net.Http;
using System.Net.Http.Headers;
using GoSaba.Models.Saba;

namespace GoSaba.Controllers.Saba
{
    class LoginController
    {
        //HTTP GET: Saba/api/login
        public async Task<string> GetCertificate(string host, string user, string password, string site)
        {
            StringBuilder getCertificate = new StringBuilder();

            if(!string.IsNullOrEmpty(host))
            {
                using(var httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(string.Format("http://{0}/", host));
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Add("user", user);
                    httpClient.DefaultRequestHeaders.Add("password", password);
                    httpClient.DefaultRequestHeaders.Add("site", site);

                    HttpResponseMessage httpResponse = await httpClient.GetAsync("Saba/api/login");

                    if(httpResponse.IsSuccessStatusCode)
                    {
                        LoginModel.GetCertificate saba = await httpResponse.Content.ReadAsAsync<LoginModel.GetCertificate>();//LoginModel.GetCertificate is model.
                        getCertificate.Append(saba.certificate);
                    }
                }
            }

            return getCertificate.ToString();
        }
    }
}

You can use this a reference in how to use a HttpClient.

like image 169
Leonel Sarmiento Avatar answered Sep 17 '26 10:09

Leonel Sarmiento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!