【问题标题】:Posting to a Web API using HttpClient and Web API method [FromBody] parameter ends up being null使用 HttpClient 和 Web API 方法 [FromBody] 参数发布到 Web API 最终为空
【发布时间】:2016-02-11 16:37:57
【问题描述】:

我正在尝试使用 HttpClient 发布到 Web API。当我在 Web API 的 Save 方法中放置断点时,[FromBody] Product 为空。这意味着我将产品发布到 Web API 的方式有问题。有人可以看看下面的代码,看看我哪里出错了。我假设它与标题和内容类型有关。

从客户端存储库到 Web API 的 POST 调用应将产品对象作为 JSON 传递:

public async Task<Product> SaveProduct(Product product)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:99999/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StringContent content = new StringContent(JsonConvert.SerializeObject(product));
        // HTTP POST
        HttpResponseMessage response = await client.PostAsync("api/products/save", content);
        if (response.IsSuccessStatusCode)
        {
            string data = await response.Content.ReadAsStringAsync();
            product = JsonConvert.DeserializeObject<Product>(data);
        }
    }
    return product;
}

Web API 控制器方法:

[HttpPost]
[Route("save")]
public IActionResult Save([FromBody]Product product)
{
    if (customer == null)
    {
        return HttpBadRequest();
    }
    _manager.SaveCustomer(product);
    return CreatedAtRoute("Get", new { controller = "Product", id = product.Id }, product);
}

[FromBody] Product 产品参数最终为空。

【问题讨论】:

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


【解决方案1】:

您是否尝试过在 fiddler 之类的工具中检查请求?正如您所指出的,它需要内容类型为 application/json 。但是您只是设置了接受标头。

试试:

StringContent content = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json");

【讨论】:

    猜你喜欢
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 2019-05-10
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多