我试图使用HttpClient对Web API进行POST.当我在Web API的Save方法中放置一个断点时,[FromBody] Product为null.这意味着我将产品发布到Web API的方式有问题.有人可以看看下面的代码,看看我可能会出错.我假设它与头文件和内容类型有关.
从客户端存储库到Web API的POST调用,该API应该通过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]产品参数最终为null.