I've been trying to send a POST request using HttpClient without a body using the PostAsync
method. However, to my utter bewildement, the request is getting sent as a GET
and not a POST
.
Naturally, the request fails with a 405 Method Not Allowed
becase the server doesn't allow GET
.
Code sample:
var response = await new HttpClient().PostAsync("https://api.creativecommons.engineering/v1/auth_tokens/token?client_id=adsf&client_secret=asdf&grant_type=client_credentials", null);
Console.WriteLine(response.RequestMessage);
Produces:
Method: GET, RequestUri: 'https://api.creativecommons.engineering/v1/auth_tokens/token/?client_id=adsf&client_secret=asdf&grant_type=client_credentials', Version: 1.1
I've also tried using Flurl, but lead to the same result (I am guessing it is using HttpClient under the hood).
Any ideas why PostAsync
is sending the request as a GET rather than POST?
Update
This question got quite a bit of hate without offering an ounce of constructive criticism... Well done StackOverflow, really well done, so much for being more welcoming...
If you come across a similar issue, here are the three things to look for:
- HttpClient will automatically redirect if the response is 301 (Redirect). It won't return you 301 as a status code!
- As it does the redirect it changes the request from POST to GET. This is technically correct, because in order to preserve the method when redirecting the server needs to return 307 and not 301.
- Check the address in the code against the one in the
RequestMessage
. This may be obvious in some cases, but in my case, the redirect involved adding a single/
not something easily visible in the debugger window!
https://api.creativecommons.engineering/v1/auth_tokens/token?client_id=adsf&client_secret=asdf&grant_type=client_credentials
https://api.creativecommons.engineering/v1/auth_tokens/token/?client_id=adsf&client_secret=asdf&grant_type=client_credentials
^