从泛型助手返回HttpResponseMessage

时间:2018-06-05 21:45:03

标签: c# .net

如果没有异常,如何在Helper类中使用以下方法返回HttpResponseMessage:

public class HttpClientHelper
{
    public static T PutAsync<T>(string resourceUri, object request)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(resourceUri);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                var responseMessage = client.PutAsJsonAsync(resourceUri, request).Result;
                return new HttpResponseMessage   // It says cannot implicitly convert to Type T
                {
                     StatusCode = responseMessage.StatusCode,
                     Content= responseMessage.Content.ReadAsStringAsync().Result.ToString()
                };

            }

            catch (Exception ex)
            {
                throw new HttpResponseException(ex.Message.ToString());
            }

        }
    }
}

HttpResponse异常:

public class HttpResponseException : Exception
{
    private string _message;

    public HttpResponseException() : base() { }
    public HttpResponseException(string message) : base(message)
    {
        this._message = message;
    }

    public override string Message
    {
        get
        {
            return this._message;
        }
    }
}

我正在尝试实现一个通用的助手类来调用我的ASP.NET Web Api。

1 个答案:

答案 0 :(得分:0)

不返回HttpResponseMessage,而是返回Web Api返回的反序列化对象:

public static T PutAsync<T>(string resourceUri, object request)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(resourceUri);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            var responseMessage = client.PutAsJsonAsync(resourceUri, request).Result;

            responseMessage.EnsureSuccessStatusCode();
            var responseData = responseMessage.Content.ReadAsStringAsync().Result;

            return JsonConvert.DeserializeObject<T>(responseData);
        }
        catch (Exception ex)
        {
            throw new HttpResponseException(ex.Message);
        }
    }
}

此外,PutAsync让我觉得我正在使用async Task方法。将其称为Put或将其设为异步。