How to read webapi responses with HttpClient in C#
On the client, include a read of the content:
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");
// Get the response
var customerJsonString = await response.Content.ReadAsStringAsync();
Console.WriteLine("Your response data is: " + customerJsonString);
// Deserialise the data (include the Newtonsoft JSON Nuget package if you don't already have it)
var deserialized = JsonConvert.DeserializeObject<IEnumerable<Customer>>(customerJsonString);
// Do something with it
}
Change your WebApi not to use your Response class but rather an IEnumerable
of Customer
. Use the HttpResponseMessage
response class.
Your WebAPI should only require:
[HttpGet, Route("GetAll")]
public IEnumerable<Customer> GetAllCustomers()
{
var allCustomers = repository.GetAll();
// Set a breakpoint on the line below to confirm
// you are getting data back from your repository.
return allCustomers;
}
Added code for a generic response class based on the discussion in the comments although I still recommend you don't do this and avoid calling your class Response. You should rather return HTTP status codes instead of your own. A 200 Ok, a 401 Unauthorised, etc. Also this post on how to return HTTP status codes.
public class Response<T>
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public IEnumerable<T> ResponseData { get; set; }
public Response(bool status, string message, IEnumerable<T> data)
{
IsSuccess = status;
Message = message;
ResponseData = data;
}
}
OR you can convert on same call
TResponse responseobject = response.Content.ReadAsAsync<TResponse>().Result;
responseJson += "hostResponse: " + JsonParser.ConvertToJson(responseobject);
//_logger.Debug($"responseJson : {responseJson}", correlationId);