【发布时间】:2021-02-24 19:57:42
【问题描述】:
我一直在尝试使用HttpClient without a body 使用PostAsync 方法发送POST 请求。然而,令我完全困惑的是,请求是以GET 而不是POST 的形式发送的。
当然,请求会以405 Method Not Allowed 失败,因为服务器不允许GET。
代码示例:
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);
生产:
Method: GET, RequestUri: 'https://api.creativecommons.engineering/v1/auth_tokens/token/?client_id=adsf&client_secret=asdf&grant_type=client_credentials', Version: 1.1
我也尝试过使用 Flurl,但结果相同(我猜它是在后台使用 HttpClient)。
知道为什么PostAsync 将请求作为 GET 而不是 POST 发送吗?
更新
这个问题在没有提供一点建设性的批评的情况下引起了相当多的仇恨......干得好 StackOverflow,干得好,非常受欢迎......
如果您遇到类似问题,请注意以下三点:
- HttpClient如果响应为 301(重定向)会自动重定向。它不会将 301 作为状态码返回给您!
- 在进行重定向时,它将请求从 POST 更改为 GET。这是technically correct,因为为了在重定向服务器时保留方法,需要返回307而不是301。
- 对照
RequestMessage中的地址检查代码中的地址。这在某些情况下可能很明显,但在我的情况下,重定向涉及添加单个/,这在调试器窗口中不容易看到!
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
^
【问题讨论】:
-
谢谢大卫。赞成。非常令人困惑的问题,尤其是在集成测试时。我花了很多时间,无法弄清楚为什么我的非常具体的 POST 请求最终会变成 GET。我在下面留下了一些设置步骤用于集成测试设置