I am using the following code snipped as part of rest client. The code works as expected. Now, I want to extend to code to return the HttpRespnseMessage along with the result. The context is in case of an error calling function will evaluate the Response message for status code and errors if any. How to return the status code along with result like <TResult, HttpResponseMessage>
.
public async Task<TResult> MakeApiCall<TResult>(string url, HttpMethod method, bool auth, string data = null) where TResult : class
{
using (var httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(0, 0, 10);
using (var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = method })
{
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// add content
if (method != HttpMethod.Get)
{
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
}
if (auth)
{
request.Headers.Add("X-Service-Token", _authUser.ServiceApiKey);
}
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await httpClient.SendAsync(request).ConfigureAwait(false);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
if (response != null)
{
Debug.WriteLine(response.StatusCode.ToString());
}
return null;
}
var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// Debug.WriteLine(stringSerialized);
// deserialize content
try
{
var desrialized_data = JsonConvert.DeserializeObject<TResult>(stringSerialized, Converter.Settings);
return desrialized_data;
}
catch (JsonReaderException ex)
{
Debug.WriteLine("JsonReaderException");
Debug.WriteLine(ex.ToString());
return null;
}
catch (JsonSerializationException ex)
{
Debug.WriteLine("JsonSerializationException");
Debug.WriteLine(ex.ToString());
return null;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return null;
}
}
}
}
Edit2: As Alexei Levenkov pointed out my question seems to be almost duplicate. I am still accepting the Michael's answer as it shows how to return multiple values in the context of Async Task