I am working on application which I have implemented a generic method which gets me response and serialize that response into response model. I am checking for error codes where I need to get the reason phrase which I want to return and to show to the user on front end But I am getting an error Here is my code. As when I write return response.ReasonPhrase
it gives me error:
Cant implicity convert string to T
public abstract class WePayResponse
{
public string ReasonPhrase { get; set; }
public string ErrorCode { get; set; }
}
List<string> ErrorCodes = new List<string> { "503", "400", "414", "415", "401", "403", "404", "405", "429", "500", "N/A" };
public async Task<T> PostRequestAsync<T>(WePayRequest<T> Request,
string wePayEndPoint,
bool? useStaging,
bool isExpectedbody = true
) where T : WePayResponse
{
StringContent httpContent = null;
if (Request != null && isExpectedbody)
{
var json = await Task.Run(() => JsonConvert.SerializeObject(Request, Formatting, JsonSerializerSettings));
httpContent = new StringContent(json, Encoding.UTF8, JsonMediaType);
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add(AppIdKey, configuration.GetValue<string>("WePay:App-Id"));
httpClient.DefaultRequestHeaders.Add(AppTokenKey, configuration.GetValue<string>("WePay:App-Token"));
httpClient.DefaultRequestHeaders.Add(ApiVersionKey, configuration.GetValue<string>("WePay:Api-Version"));
httpClient.DefaultRequestHeaders.Add(UniqueKey, Guid.NewGuid().ToString());
using (HttpResponseMessage response = await httpClient.PostAsync(GenerateWePayEndPointUrl(wePayEndPoint, useStaging), httpContent))
{
if (response.IsSuccessStatusCode)
return await response.Content.ReadAsAsync<T>();
if (ErrorCodes.Contains(Convert.ToInt32(response.StatusCode).ToString()))
{
return response.ReasonPhrase; /// -- error
// --- How to get generice response
// except me to use await ...
}
throw new Exception(response.ReasonPhrase);
}
}
}
I have got it working. Here is updated code. May be this can help someone in future