首页 > 解决方案 > 从通用助手返回 HttpResponseMessage

问题描述

当没有异常时,如何在 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。

标签: c#.net

解决方案


不返回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要么让它异步。


推荐阅读