【发布时间】:2021-09-18 00:36:40
【问题描述】:
这是 POST 请求,它有效。
curl -X POST --header 'Accept: application/json'
'http://mywebsite.com/api/CompleteService?refId=12345&productPrice=600'
如何使用C# => HttpClient => client.PostAsync() 方法发送这个请求?
两种方法都试过了,都失败了。
方法 1(失败,响应 404)
string url = "http://mywebsite.com/api/CompleteService";
string refId = "12345";
string price= "600";
string param = $"refId ={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;
这只有在 API 接受请求正文而不是查询字符串时才有效。
方法 2(失败,响应 404) https://stackoverflow.com/a/37443799/7768490
var parameters = new Dictionary<string, string> { { "refId ", refId }, { "productPrice", price} };
var encodedContent = new FormUrlEncodedContent(parameters);
HttpResponseMessage response = client.PostAsync(url, encodedContent)
【问题讨论】:
-
可能你的端点有问题。
-
不,它已经在 Swagger、Postman、Axios 上进行了测试。
-
从 404 开始,您必须发布您的控制器和操作标头
标签: c# post dotnet-httpclient