我正在尝试通过 httpclient 发布匿名对象,但是当它到达 Controller 时 orderId 为空并且集合为空。
public async Task<Response> CancelOrderAsync(int orderId, ICollection<int> ids)
{
Response result = null;
using (IHttpClient client = HttpClientFactory.CreateHttpClient())
{
var obj = new {OrderId = orderId, Ids = ids};
string json = JsonConvert.SerializeObject(obj);
HttpContent postContent = new StringContent(json, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync($"{url}/admin/cancel", postContent).ConfigureAwait(false))
{
if (response != null && response.IsSuccessStatusCode)
{
...
}
}
}
return result;
}
// Controller
[HttpPost]
[ActionName("cancel")]
public async Task<Response> Cancel(int orderId, ICollection<int> ids)
{
// order is null, collection empty
...
编辑:
为简单起见,将我的 Controller 更改为此
[HttpPost]
[ActionName("cancel")]
public async Task<SimpleResponse> Cancel(int orderId)
通过 Postman,我正在发布这个正文:
{
"orderId": "12345"
}
仍然,orderId 以 0(零)形式出现??
最佳答案
服务器端的 Controller Action 需要一个具体的类型来读取请求的整个主体
public class Order {
public int OrderId { get; set; }
public int[] Ids { get; set; }
}
这主要是因为该操作只能从正文中读取一次。
将操作更新为...
[HttpPost]
[ActionName("cancel")]
public async Task<Response> Cancel([FromBody]Order order) {
if(ModelState.IsValid) {
int orderId = order.OrderId;
int[] ids = order.Ids;
//...
}
//...
}
示例中用于发送请求的原始代码将按原样工作,但如前所述,它可以改进。
关于c# - 通过 HttpClient 发布匿名对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49491836/