发布使用Web API的HttpClient和Web API方法[FromBody]参数最终被空

编程入门 行业动态 更新时间:2024-10-25 18:32:49
本文介绍了发布使用Web API的HttpClient和Web API方法[FromBody]参数最终被空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图张贴到使用HttpClient的一个Web API。当我把一个断点在Web API的保存方法[FromBody]产品为null。这意味着什么是错的,我过到Web API发布的产品的方式。是否有人可以看看下面的code和看到我可能是想错了。我假设它是值得做的标题和内容类型。

I am attempting to POST to a Web API using the HttpClient. When I put a breakpoint in the Save method of the Web API the [FromBody] Product is null. This means that something is wrong with the way I am posting the product over to the Web API. Can someone please take a look at the below code and see where I might be going wrong. I am assuming it is something to do with headers and content types.

从客户端库到Web API POST调用应通过传递产品对象作为JSON:

public async Task<Product> SaveProduct(Product product) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("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]产品的产品参数最终被空。

[FromBody] Product product parameter ends up being null.

推荐答案

你试过在检查像小提琴手的要求?它需要的内容类型是应用程序/ JSON正如你所指出。但是你只设置accept头。

Have you tried inspecting the request in something like fiddler? It needs the content-type to be application/json as you have pointed out. But you are only setting the accept header.

尝试:

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

更多推荐

发布使用Web API的HttpClient和Web API方法[FromBody]参数最终被空

本文发布于:2023-10-12 01:21:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   方法   API   Web   FromBody

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!