Search code examples
c#jsonrestdotnet-httpclientbasecamp

REST JSON GET - 400 Bad Request


I am working with the Basecamp API which is a REST (JSON) API using basic HTTP authentication over HTTPS.

This should be a GET request but when I run my code using GET I am receiving:

Cannot send a content-body with this verb-type

When I run it as a POST, I receive:

{"status":"400","error":"Bad Request"}

Does anyone know why this may be occurring?

    using (var httpClient = new HttpClient()) {

        string userName = "[email protected]";
        string password = "somepassword";

        var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password)));

        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

        HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://correctUrlHere);
        requestMessage.Headers.Add("User-Agent", "TheProject ([email protected])");
        requestMessage.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

        var response = await httpClient.SendAsync(requestMessage);

        var responseContent = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseContent);
    }

In this code I obviously swapped out the username, password, project name, and URL but in the actual code they are all correct.


Solution

  • GET requests must pass their parameters as url query and not as request body.

    http://example.com?p1=1&p2=helloworld 
    

    If you don't have any content, as your example suggests, omit setting it on the request.

    The BadRequest result indicates some error with your payload (again: content seems to be empty).