简体   繁体   中英

Return HttpResponseMessage from generic helper

How can I make following method in Helper class to return HttpResponseMessage in following code block, when there is no exception:

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 Exception:

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;
        }
    }
}

I am trying to implement a generic helper class to call my ASP.NET Web Api.

Instead of returning the HttpResponseMessage , return the deserialized object returned by the 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);
        }
    }
}

Also, PutAsync makes me think I am working with an async Task method. Either call it Put or make it asynchronous.

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