我正在尝试使用 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/