Answered by:
How to read web api response with HttpClient c#

Question
-
User264732274 posted
i am fairly new in web api. i have developed small web api which has few action and return my custom class called Response.
Response class look like
public class Response { bool IsSuccess=false; string Message; object ResponseData; public Response(bool status, string message, object data) { IsSuccess = status; Message = message; ResponseData = data; } }
my web api with few actions
[RoutePrefix("api/customer")] public class CustomerController : ApiController { static readonly ICustomerRepository repository = new CustomerRepository(); [HttpGet, Route("GetAll")] public Response GetAllCustomers() { return new Response(true, "SUCCESS", repository.GetAll()); } [HttpGet, Route("GetByID/{customerID}")] public Response GetCustomer(string customerID) { Customer customer = repository.Get(customerID); if (customer == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return new Response(true, "SUCCESS", customer); //return Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet, Route("GetByCountryName/{country}")] public IEnumerable<Customer> GetCustomersByCountry(string country) { return repository.GetAll().Where( c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase)); } }
now where i stuck is that i do not know how to read response data return from web api actions and extract json from my response class. after getting json how could i
deserialize
that json to customer class.
this way i am calling my web api function.
private void btnLoad_Click(object sender, EventArgs e) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:8010/"); // Add an Accept header for JSON format. //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // List all Names. HttpResponseMessage response = client.GetAsync("api/customer/GetAll").Result; // Blocking call! if (response.IsSuccessStatusCode) { Console.WriteLine("Request Message Information:- \n\n" + response.RequestMessage + "\n"); Console.WriteLine("Response Message Header \n\n" + response.Content.Headers + "\n"); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } Console.ReadLine(); }
just guide me sample code
1) how to get response class which web api action returns at client side
2) how could i extract json from response class
3) how to deserialize the json to customer class at client side
thanks
Friday, August 26, 2016 9:02 AM
Answers
-
User36583972 posted
Hi sudip_inn,
You can try the following code.
using (var client = new System.Net.Http.HttpClient()) { // HTTP POST client.BaseAddress = new Uri("baseUrl"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("/api/Customer/GetAll").Result; string res = ""; using (HttpContent content = response.Content) { // ... Read the string. Task<string> result = content.ReadAsStringAsync(); res = result.Result; } }
Best Regards,
Yohann Lu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, August 29, 2016 1:22 AM
All replies
-
User-1404113929 posted
hi,
please find bellow code it will helpfull for you.
public ActionResult Index() { HttpClient client = new HttpClient(); ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; HttpWebRequest request = this.GetRequest("http://localhost:50250/api/Instance"); WebResponse webResponse = request.GetResponse(); var responseText = new StreamReader(webResponse.GetResponseStream()).ReadToEnd(); return View(); } private HttpWebRequest GetRequest(string url, string httpMethod = "GET", bool allowAutoRedirect = true) { Uri uri = new Uri(url); HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"; request.Timeout = Convert.ToInt32(new TimeSpan(0, 5, 0).TotalMilliseconds); request.Method = httpMethod; return request; }
Thanks,
Murali
Friday, August 26, 2016 9:30 AM -
User264732274 posted
i want to use HttpClient instead of HttpWebRequest class to call web api action.
Friday, August 26, 2016 11:35 AM -
User36583972 posted
Hi sudip_inn,
You can try the following code.
using (var client = new System.Net.Http.HttpClient()) { // HTTP POST client.BaseAddress = new Uri("baseUrl"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("/api/Customer/GetAll").Result; string res = ""; using (HttpContent content = response.Content) { // ... Read the string. Task<string> result = content.ReadAsStringAsync(); res = result.Result; } }
Best Regards,
Yohann Lu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, August 29, 2016 1:22 AM