c# - 使用 HttpClient 和 Web API 方法 [FromBody] 参数发布到 Web API 最终为空

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

我正在尝试使用 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 Controller 方法:

[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 产品参数最终为空。

最佳答案

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

尝试:

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

关于c# - 使用 HttpClient 和 Web API 方法 [FromBody] 参数发布到 Web API 最终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35344981/

相关文章:

c# - 如何创建没有选项卡标题的 TabControl?

c# - Angular 7 与 SignalR Hub 的连接失败

c# - 范围验证 - 对规则进行异常(exception)处理

c# 数组声明语法 vs c++ 数组声明语法

asp.net - html 表单的 onkeydown 事件在 IE 7 或 FF 3 中未触发

c# - 在 ASP .NET 应用程序中每 24 小时/每个用户自动触发事件一次

asp.net - 更新面板不起作用,不知道为什么

asp.net-mvc - 从 MVC Controller 调用 Web API 来构建和传递模型以查看

c# - 目前仅支持HTTP/1.0和HTTP/1.1版本请求

c# - 使用 ASP.NET Web API 进行依赖注入(inject)