API的HttpClient和Web

API的HttpClient和Web

本文介绍了发布使用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("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]产品的产品参数最终被空。

[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]参数最终被空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:30