0

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"

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.