C# HttpClient.SendAsync causes error, cannot send a content-body with this verb-type

4.2k views Asked by At

I am getting error cannot send a content-body with this verb-type. I am calling a GET Endpoint from a C# VSTO desktop application. What am I doing wrong.

public static string GetCentralPath(LicenseMachineValidateRequestDTO licenseMachine)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization =    new AuthenticationHeaderValue("Bearer", Properties.Settings.Default.Properties["JWT"].DefaultValue.ToString());
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri($"{Constants.URL.APIBase}licensemachine/GetCentralPath"),
            Content = new StringContent(JsonConvert.SerializeObject(licenseMachine), Encoding.UTF8, "application/json"),
        };
        
        using (HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult()) // Causing ERROR
        {
            var result = GetStringResultFromHttpResponseMessage(response, true);
            if (string.IsNullOrEmpty(result))
                return null;
            return JsonConvert.DeserializeObject<string>(result);
        }
    }
}

The end point looks like the following:

[HttpGet("GetCentralPath")]
public async Task<IActionResult> GetCentralPath(LicenseMachineValidateRequestDTO dto)
{
    // Some code
}
1

There are 1 answers

3
Serge On

fix the action, you cannot send body data with get, see this post HTTP GET with request body

[HttpPost("GetCentralPath")]
public async Task<IActionResult> GetCentralPath(LicenseMachineValidateRequestDTO dto)

and fix request , replace Method = HttpMethod.Get with Post, this is what generates an error

var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri($"{Constants.URL.APIBase}licensemachine/GetCentralPath"),
            Content = new StringContent(JsonConvert.SerializeObject(licenseMachine), Encoding.UTF8, "application/json"),
        };