简体   繁体   English

httpClient.PostAsync() 无论如何都会执行 GET 请求

[英]httpClient.PostAsync() performs GET request anyway

I really am not sure what is happening.我真的不确定发生了什么。
I'm using an HttpClient to post XML content to a remote server using the PostAsync method like this:我正在使用 HttpClient 使用PostAsync方法将 XML 内容发布到远程服务器,如下所示:

using var content = new StringContent(payload, Encoding.UTF8, "application/xml");
using var response = await _httpClient.PostAsync(string.Empty, content);

... where payload is a string, and relative uri is empty because I just need to call base uri of httpclient. ...其中payload是一个字符串,而相对uri是空的,因为我只需要调用httpclient的base uri。

I can perform same request in Postman and it works fine.我可以在 Postman 中执行相同的请求,并且工作正常。
The issue is, for some reason httpclient actually performs a GET request instead of POST, and ignores content whatsoever:问题是,由于某种原因,httpclient 实际上执行的是 GET 请求而不是 POST,并且忽略了任何内容:

截屏

I've checked in Postman, and it seems like it is a normal response from the server to GET request.我检查了 Postman,这似乎是服务器对 GET 请求的正常响应。

I've also tried我也试过

using var response = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, string.Empty){Content = content});

... and it gives the same result. ...它给出了相同的结果。

This looks like a very weird issue to me, as I've never seen http client behaving like this in the past.这对我来说似乎是一个非常奇怪的问题,因为我过去从未见过 http 客户端的行为如此。 Could anyone please explain why is this happening?谁能解释一下为什么会这样? Thanks!谢谢!

OK, so the issue was actually with server.好的,所以问题实际上与服务器有关。

It redirected all the requests with URLs not ending with "/", like http://address.com/page to the same address but ending with "/" - http://address.com/page/ , and lost the method and content in process.它将所有 URL 不以“/”结尾的请求,例如http://address.com/page到相同的地址但以“/”结尾 - http://address.com/page/ ,并丢失了方法和正在处理的内容。

As @Jimi mentioned, the RequestMessage field in HttpResponseMessage contains the info about the last request that reached the server, therefore initial request data was lost, and I mistook it for HttpClient making wrong requests.正如@Jimi 提到的,HttpResponseMessage 中的 RequestMessage 字段包含有关到达服务器的最后一个请求的信息,因此初始请求数据丢失了,我误认为 HttpClient 发出了错误的请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM