Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting to a Web API using HttpClient and Web API method [FromBody] parameter ends up being null

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.

POST call from a client repository to the Web API which should pass the product object through as 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 Method:

[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 product parameter ends up being null.

like image 877
Blake Rivell Avatar asked Feb 11 '16 16:02

Blake Rivell


People also ask

Why your FromBody parameter is always null?

If you need to get multiple values from the request body, define a complex type. But still the value of email is NULL . The JavaScript code is part of generic method we use, so that's why the content-type is set to application/json; charset=utf-8 .

How do I pass a null parameter in Web API?

Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters.

What is FromBody in Web API?

Using [FromBody] When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

Can we declare FromBody attribute on multiple parameters?

The [FromBody] attribute can be applied on only one primitive parameter of an action method. It cannot be applied to multiple primitive parameters of the same action method.


1 Answers

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.

Try:

StringContent content = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json");
like image 140
Frode Avatar answered Oct 19 '22 03:10

Frode