httpClient.PostAsync() performs GET request anyway

人走茶凉 提交于 2021-01-28 18:20:30

问题


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:

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.

I can perform same request in Postman and it works fine.
The issue is, for some reason httpclient actually performs a GET request instead of POST, and ignores content whatsoever:

I've checked in Postman, and it seems like it is a normal response from the server to GET request.

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. Could anyone please explain why is this happening? Thanks!


回答1:


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.

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.



来源:https://stackoverflow.com/questions/62579558/httpclient-postasync-performs-get-request-anyway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!