REST JSON GET - 400 Bad Request - c#

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 = "someone#someone.com";
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 (someone#someone.com)");
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.

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

Related

http response is 500 on code parameter request

This is a http request to the https://auth.monday.com/oauth2/authorize endpoint on asp.net 6. It should get the code parameter from that endpoint but it's returning a 500 response with html for some reason. This is part of my code grant flow because the API has oauth2.0.
public async Task<string> GetCode(string clientId, string redirect_uri)
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"https://auth.monday.com/oauth2/authorize{clientId}");
string json =
JsonSerializer.Serialize(
new
{
query = "code"
}
);
request.Content = new StringContent(json,
Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
var responseText = await response.Content.ReadAsStringAsync();
return responseText;
}
Are you missing a / in your endpoint by any chance? Should it not be https://auth.monday.com/oauth2/authorize/{clientId}?
HTTP 500 is an internal server error, this means that the server was unable to handle your request properly. If you have access to the server then I would look there as to why it was unable to handle your request. I don't see anything wrong in your request.

Set request header for POST method using Content-Type, Authorization-User and Authorization-Key in HTTPClient C#

I spent a lot of time looking for an answer, but I didn't find it. I need to send a POST to an API using HTTPClient in C# in the following format:
POST endpoint URL
Content-Type: application/json
Authorization-User: email address
Authorization-Key: EMP-generated key
{
request body
}
Authorization-User and Authorization-Key are required in headers and cannot be replaced by username and password name.
When I use my code described below I got the exception in line client.DefaultRequestHeaders.Add: "Incorrect header name. Check if request headers are used with HttpRequestMessage, response headers with HttpResponseMessage and content headers with HttpContent objects".
Can someone help me?
My code:
var client = new HttpClient();fdaJsonCons ofdaJson = new fdaJsonCons();
fdaFilters oFdaFilter = new fdaFilters();
ofdaJson.filters = oFdaFilter;
string stJson = JsonConvert.SerializeObject(ofdaJson);
string vContentType = "application/json";
var content = new StringContent(JsonConvert.SerializeObject(stJson), Encoding.Default, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(vContentType));
client.DefaultRequestHeaders.Add("Content-Type", String.Format("Basic {0}", "application/json"));
client.DefaultRequestHeaders.Add("Authorization", String.Format("Authorization-User {0}", "my-email"));
client.DefaultRequestHeaders.Add("Authorization", String.Format("Authorization-Key {0}", "my-keyvalue"));
var result = await client.PostAsync(url, content);
var result_string = await result.Content.ReadAsStringAsync();

404 when accessing Design Automation API v3 through HttpClient

Running calls to the Design Automation API in Postman works just fine but when I try to make the same calls in C# using HttpClient they fail with a 404 that seems to actually hide an authentication error:
{
"developerMessage":"The requested resource does not exist.",
"userMessage":"",
"errorCode":"ERR-002",
"more info":"http://developer.api.autodesk.com/documentation/v1/errors/err-002"
}
That link leads to an authentication error:
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>1F52E60A45AEF429</RequestId>
<HostId>
[ Some base64 ]
</HostId>
</Error>
I'm following examples for how to use HttpClient, but I may be missing something. I successfully get the access token, run
var client = new HttpClient
{
BaseAddress = new Uri("https://developer.api.autodesk.com/da/us-east")
};
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(TokenType, AccessToken);
then
var result = await client.GetAsync("/v3/forgeapps/me");
and the above json is the result's content. I use the same access token in Postman and it works.
I would wrap up the endpoint, headers, and httpmethod in the HttpRequestMessage. Then send it and assign it to HttpResponseMessage.
var client = new HttpClient
{
BaseAddress = new Uri("https://developer.api.autodesk.com/da/us-east/")
};
//throw the endpoint and HttpMethod here. Could also be HttpMethod.Post/Put/Delete (for your future reference)
var request = new HttpRequestMessage(HttpMethod.Get, "v3/forgeapps/me");
//also maybe try throwing the headers in with the request instead of the client
request.Headers.Add(TokenType, AccessToken);
// send the request, assign to response
HttpResponseMessage response = await client.SendAsync(request);
//then, we can grab the data through the Content
string result = await response.Content.ReadAsStringAsync();

How do I programmatically login with IdentityServer4 using code

So here's my code that I'm trying.
Uri uri = new Uri(_environmentConfiguration.AuthorityLoginRequestUrl);
string content = $#"Username={ userID }&Password={ userPassword }";
var request = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
_httpClient.SetBearerToken(token.AccessToken);
var response = await _httpClient.PostRequest(uri, request);
The response I get back is a status 400: Bad Request.
Obviously there is something wrong with the request. Either headers/cookies and/or query.
Any ideas?

403 error when trying to get data from Reddit API

I am using oAuth to authenticate my app. I managed to get a code, access_token and refresh_token. So the next step would be trying to get info about the current user.
public async void GetCurrentUser()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);
var response = await client.GetAsync("https://oauth.reddit.com/api/v1/me");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
}
}
}
This is the method I am using to do that. However the response is always an 403 (Forbidden) error code. Any idea what could be wrong? The access_token is what I got when I made a request to https://oauth.reddit.com/api/v1/access_token
I think the token is correct because when I create the same request with Fiddler it works.
ANSWER:
Fixed it by adding a custom user-agent
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, _endpointUri + "me");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
request.Headers.Add("User-Agent", Uri.EscapeDataString("android:com.arnvanhoutte.redder:v1.2.3 (by /u/nerdiator)"));
var response = await client.SendAsync(request);

Categories

Resources