NMK
NMK

Reputation: 1020

HttpClient to retrieve web API response

I want a generic function that will send a http request & returns a HttpResponseMessage. Here is what I got now.

        public static HttpResponseMessage SendRequest(string actionUri, string baseAddress, HttpRequestMessage request)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseAddress);

            HttpResponseMessage response = null;

            foreach (var header in request.Headers)
            {
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }

            if (request.Method == HttpMethod.Get)
            {
                response = client.GetAsync(actionUri).Result;
            }

            if (request.Method == HttpMethod.Post)
            {
                response = client.PostAsync(actionUri, request.Content).Result;
            }

            if (request.Method == HttpMethod.Put)
            {
                response = client.PutAsync(actionUri, request.Content).Result;
            }

            if (request.Method == HttpMethod.Delete)
            {
                response = client.DeleteAsync(actionUri).Result;
            }
            return response;
        }
    }

Above function can be written as below

    public static HttpResponseMessage SendRequest1(string actionUri, string baseAddress, HttpRequestMessage request)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseAddress);
            return client.SendAsync(request).Result;

        }
    }

Is there any issues using the second approach versus the explicit calls based on the http verb. For some requests I am getting error for GET requests as "Cannot send a content-body with this verb-type"

Upvotes: 0

Views: 421

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26436

The second piece of code looks fine to me; GET requests should never contain a content-body.

In the first example you're ignoring the content-body in case of a GET request, in the second example you're letting the framework throw an exception (which it was designed to do).

Upvotes: 1

Related Questions