Search code examples
c#asp.net-core

Third party API returns httpresponsemessage. Can someone help me to understand how to extract data out of httpresponsemessage and return generic type


public async Task<>GetLandProperty(string num)
{
 var request = new HttpRequestMessage(HttpMethod.Get, _httpClient.BaseAddress+relativeurl);
// added required headers here.
 var response = await _httpClient.SendAsync(request);
}

Now here response is httpresponsemessage. I don't understand how to extract data out of response and deserialize it. Probably I can create class, fetch response's content and deserialise it but what to do if it return failure response or exception. how to return generic type in this case.


Solution

  • This is related to your api code. You can catch the exception information and return different information by setting the HttpStatusCode of HttpResponseMessage in the api side.

    In the GetLandProperty method, you can set the return type to object to return different content.

    Determine the returned content by judging the status of IsSuccessStatusCode of response. If the status is true, use the type returned by deserialize and return the corresponding object. If it is false, return the response directly.

    public async Task<object> GetLandProperty()
        {
            Product product = null;
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("url");
                var request = new HttpRequestMessage(HttpMethod.Get, client.BaseAddress);
                var response = await client.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    string responseString = response.Content.ReadAsStringAsync().Result;
                    Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(responseString);
                    product = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(responseString);
                    return product;
                }
                return response;
    
            } 
        }
    

    My api code:

       [HttpGet]
        public HttpResponseMessage Get(int id)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            Product persona = _context.Product.FirstOrDefault(p => p.DataID == id);
            if (persona != null)
            {
                response.Content = new StringContent(JsonConvert.SerializeObject(persona));
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                return response;
            }
            else
            {
                response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                response.Content = new StringContent("error message");
                return response;
            }
    
        }
    

    Update

    Another method to receive GetLandProperty method returned content:

       public async Task<object> CallTest()
            {
                var obj = await GetLandProperty();
                if(obj is Product)
                {
                    Product product= (Product)obj;
                    // save data to db
    
                }
                else
                {
                    //do other operations
                    return obj;
                }
    
    
            }
    

    Here is the test result by postman: enter image description here