httpClient.PostAsync()仍然执行GET请求 [英] httpClient.PostAsync() performs GET request anyway

查看:70
本文介绍了httpClient.PostAsync()仍然执行GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不确定发生了什么.
我正在使用HttpClient使用 PostAsync 方法将XML内容发布到远程服务器,如下所示:

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

...其中 payload 是一个字符串,相对uri为空,因为我只需要调用httpclient的基本uri.

... where payload is a string, and relative uri is empty because I just need to call base uri of httpclient.

我可以在邮递员中执行相同的请求,并且效果很好.
问题是,出于某种原因,httpclient实际上执行了GET请求而不是POST,并且忽略了任何内容:

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:

我已经签到Postman,看来这是服务器对GET请求的正常响应.

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

我也尝试过

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

...并且给出相同的结果.

... and it gives the same result.

这对我来说似乎是一个很奇怪的问题,因为我以前从未见过HTTP客户端的行为.谁能解释为什么会这样吗?谢谢!

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!

推荐答案

好的,所以问题实际上出在服务器上.

OK, so the issue was actually with server.

它将所有不以"/"结尾的URL(如 http://address.com/page )URL重定向到相同的地址,但以"/"结尾.- http://address.com/page/,并且丢失了正在处理的方法和内容.

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.

如@Jimi所述,HttpResponseMessage中的RequestMessage字段包含有关到达服务器的最后一个请求的信息,因此,初始请求数据丢失了,我误以为HttpClient发出了错误的请求.

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.

这篇关于httpClient.PostAsync()仍然执行GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆