iaacp
iaacp

Reputation: 4845

Request Body is null in controller?

I'm calling a POST controller action using fetch, but in the controller, the body appears to be null.

Here's my fetch code snippet - this is in a .net core Vue project. It's a typescript file.

var data = JSON.stringify(this.newProduct);
console.log(data)

fetch('api/Product/AddNewProduct', {
     method: 'POST',
     body: data,
     headers: {
         'Content-Type': 'application/json'
     }
}).then(res => res.json())
       .then(response => console.log('Success:', JSON.stringify(response)))
       .catch(error => console.error('Error:', error));

And here's the request (and payload) as I can see it in Firefox:

Request

But in my .net core backend, when the API gets hit, I can't seem to get the value of the body or anything in the request.

[HttpPost("[action]")]
public IActionResult AddNewProduct([FromBody] string body)
{
   Product newProduct;
   try
   {
     /*Added the below snippet for testing, not sure if actually necessary */
       using (var reader = new StreamReader(Request.Body))
       {
           var requestBody = reader.ReadToEnd();
           // Do something
        }

        //Convert the request body to an object
        newProduct = JsonConvert.DeserializeObject<Product>(body);
    }
    catch (Exception e)
        {
             return new BadRequestResult();
         }

Here, in my debugger, both body and requestBody are null. Any ideas?

Upvotes: 1

Views: 13934

Answers (2)

Sith2021
Sith2021

Reputation: 3726

Add to headers Accept

headers: {
    'Content-Type': 'application/json', 
    'Accept': 'application/json',
},

Upvotes: 2

Simply Ged
Simply Ged

Reputation: 8662

.NET isn't seeing you passing a string, it sees a JSON because you pass the Content-Type header of application/json so it will try to deserialize it and map it to your request object. In your case, because your parameter is string body the parser tries to map the JSON object to your string and fails - so it passes null.

You can try and change the request to pass text/plain as the content-type (or remove the content-type header) or change your API parameter to the object you are sending:

public IActionResult AddNewProduct([FromBody] Product newProduct)
{
    ...
}

Upvotes: 8

Related Questions