404 when accessing Design Automation API v3 through HttpClient - c#

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();

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.

I am getting StatusCode: 401 "Unauthorized" in a HttpClient.PostAsync (C#)

I am trying to use an Api Rest (IGDB) making an Http Post Request with HttpClient; this request needs to have a key and a body. I am providing the key in HttpClient.DefaultRequestHeaders.Authorization, but I am getting a 401 status code, I know that the key works because I have used it in Postman and It worked fine, so I must be implementing it wrong.
My code:
private async Task<string> ConsumeApi()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Key Name", "Key Value");
//Makes the client request only Json data
//client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("aplication/json"));
string theUri = "https://api-v3.igdb.com/games";
var stringcontent = new StringContent("fields name", UnicodeEncoding.UTF8,"application/json");
var response = await client.PostAsync("https://api-v3.igdb.com/games", stringcontent);
return response.ToString();
}
And these are Postman pictures of what I am trying to implement (works fine):
AuthenticationHeaderValue
is not setting a header but is an authorization header. Set a normal header value, not one prefixed with Authentication.

Why getting 401 when trying validating Token

I have a Bearer token and need to validate it against a api and validateToken endpoint. The endpoint aspects a json like that:
{
"jwtToken": "my token"
}
At the swagger I try successful this endpoint using url
http://10.212.226.31:5022/api/v1/validateToken
But I need to validate from code and there I get a 401 'Unauthorized'.
HttpClient client = new HttpClient
{
BaseAddress = new Uri("http://10.212.226.31:5022/")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string token = accessToken.Replace("Bearer ", "");
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/v1/validateToken", token);
At the response object I get the 401.
What is wrong? Some thing about the json?
How to hand over the right stuff to the endpoint?
Additions:
I work remote on a virtual machine from a costumer and he does not allow installing software. Fiddler and co is not available.
I tried also this, but it's not working:
ValidateTokenRequest tokenJson = new ValidateTokenRequest
{
jwtToken = token
};
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/v1/validateToken", tokenJson);
I needed to authenticate my self at the endpoint, to add the token to the header.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Now it works. Thanks to everybody!

Setting up a REST Client Application (Post) from a Web API

I've been having a few issues in trying to retrieve the results of a POST operation from a Web Service.
I have been using a chrome extension to test the API Services and they are working there. However I've been having problems on implementing it in code.
This is an example of usage of the chrome extension:
What I'm trying to retrieve on code, is the last part, the json array that the POST operation generates, where it says accessToken.
However, in the code that I've been using below, I've only had access to the status (200 OK) etc.
Here's a preview of the code I am using:
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url.Text);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(header.Text));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url.Text);
request.Content = new StringContent(body.Text, Encoding.UTF8, header.Text);
client.SendAsync(request)
.ContinueWith(responseTask =>
{
MessageBox.Show(responseTask.Result.Content.Headers.ToString());
}
);
}
The Header.Text is exactly "application/json", the body.Text is body which has those various properties such as username and password (in string format) and url.Text contains the complete URL to call the Web service.
I'd like to know what I'm doing wrong with my code, and what can I do to obtain that json array that contains the accessToken
In your code you need to use ReadAsStringAsync method to convert your HttpContent object to string/json. For example:
client.SendAsync(request)
.ContinueWith(responseTask =>
{
var jsonString = responseTask.Result.Content.ReadAsStringAsync().Result;
MessageBox.Show(jsonString);
});
then you can convert you jsonString as you need.

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

Categories

Resources