c# - 通过 HttpClient 发布匿名对象

标签 c# .net asp.net-web-api

我正在尝试通过 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/

相关文章:

c# - 当参数直接定义为方法参数而不是模型时,IHttpActionResult 结果无法绑定(bind)请求正文参数

c# - 使用 .NET Native 工具链构建会导致动态对象中缺少属性的错误

c# - Visual Studio 2013 .aspx 智能感知不工作

.net - Microsoft.ApplicationInsights.Log4NetAppender

c# - 从字符串变量创建对类的引用

c# - Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware 警告 : 0 : invalid bearer token received

C# 使用不同方法创建包含可访问变量的列表

c# - 如何在asp.net c#中验证文本框只输入几个选项​​?

c# - TCP 套接字服务器 Windows 应用程序

javascript - 我们如何将 Vue JS 与 ASP.NET MVC 和 nuget 包集成