简体   繁体   中英

How to get string response from generic asyn method

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

 public abstract class WePayResponse
{
    public string error_code { get; set; }
    public string error_message { get; set; }
    public List<Detail> details { get; set; }
}
public class Detail
{
    public List<string> target { get; set; }
    public string target_type { get; set; }
    public string reason_code { get; set; }
    public string message { get; set; }
}


   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>();
                     else
                {
                    var result = await response.Content.ReadAsAsync<T>();
                    throw new Exception($"wepay-{result.details.Select(x => x.message).FirstOrDefault()}");
                }
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM