using EasyDevCore.Common;
using System.Net;
using System.Net.Http.Json;
namespace EasyDevCore.Remote.HttpAccess
{
///
///
///
public static class HttpClientResponseExtensions
{
///
/// Gets the json asynchronous.
///
/// The type of the result.
/// The response.
/// The default value.
///
public static async Task GetJsonAsync(this Task response, TResult defaultValue = default)
{
try
{
var value = await response;
if (value.IsSuccessStatusCode)
{
return await value.Content.ReadFromJsonAsync();
}
else
{
return defaultValue;
}
}
catch
{
if (defaultValue != null)
{
return defaultValue;
}
throw;
}
}
private static async Task GetValueFromJsonContent(HttpContent content)
{
using (var stream = content.ReadAsStreamAsync())
{
var result = HttpAccessSetup.JsonSerializerResponse.Deserialize(await stream);
return result;
}
}
private static TResult DefaultFailureHandler(Exception e)
{
return (TResult)Activator.CreateInstance(typeof(TResult), e);
}
///
/// Makes the result.
///
/// The type of the result.
/// The response.
/// The failure.
///
public static async Task MakeResultAsync(this Task response, Func failure = null)
where TResult : new()
{
try
{
if (failure == null)
{
failure = DefaultFailureHandler;
}
var value = await response;
if (value.IsSuccessStatusCode)
{
return await GetValueFromJsonContent(value.Content);
}
else
{
TResult result = default;
string errorMessage = string.Empty;
int errorNum = 0;
int statusNum = (int)value.StatusCode;
if (value.Content.Headers.ContentLength > 0)
{
try
{
result = await GetValueFromJsonContent(value.Content);
}
catch
{
errorMessage = await value.Content.ReadAsStringAsync();
}
}
if (result == null)
{
errorNum = statusNum;
}
else if (result.GetType().HasInterface(typeof(IResult<>)))
{
bool isError = result.GetPropertyValue("IsError");
if (isError)
{
string resultCode = result.GetPropertyValue("ResultCode");
errorMessage = result.GetPropertyValue("Message");
errorNum = int.TryParse(resultCode, out var resultNum) ? resultNum : statusNum;
}
}
Exception exception = new Exception(string.IsNullOrWhiteSpace(errorMessage) ? value.StatusCode.ToString() : errorMessage);
exception.HResult = errorNum == 0 ? statusNum : errorNum;
return failure(exception);
}
}
catch (Exception ex)
{
return failure(ex);
}
}
}
}