Sending list of integers to REST API throws 415 (Unsupported Media Type)

Viewed 223

I'm experimenting with reactjs and .net core web api, and I'm trying to send simple list of integer to the rest api. Throught postman I did it without any issues, but when I try to do it from my react js code I'm getting 415 error in a console:

This is how my method on the API looks:

   // DELETE api/SiteUsers/delete
   [HttpPost("delete")]
   public async Task<ActionResult> DeleteSiteUsers(DeleteValuesDto deleteValues, CancellationToken cancellationToken)
   {
            
        return NoContent();
   }

Here is how my DeleteValuesDto looks like:

enter image description here

On the frontend I made simple method which should make an api call to rest api:

 const handleDelete = async () => {
    var deleteValues = {
      values: selectedRows,
    };
    await deleteSiteUser(deleteValues);
  };

Here is my deleteSiteUser method on frontend:

export const deleteSiteUser = (deleteValues) => {
  console.log('deleteValues', deleteValues);
  return axiosWrapper.request({
    url: `/SiteUsers/delete`,
    method: 'POST',
    deleteValues,
  });
};

Here are the results of console log:

enter image description here

I thought this would be very simple, but I find out it isn't actually :/

2 Answers

You need to send the data in the named data property as per the documentation (https://github.com/axios/axios#request-config)

export const deleteSiteUser = (deleteValues) => {
  console.log('deleteValues', deleteValues);
  return axiosWrapper.request({
    url: '/SiteUsers/delete',
    method: 'POST',
    data: deleteValues,
  });
};

If you are not setting the data property, the payload is empty. The most likely outcome of this is, that the Conent-Type header is not set and thus Asp.Net cannot decide how to parse the request body and then throws that error. You could just check that in your developer console in Chrome, then set the data property and check the Content-Type header for that reqeust as well.

You're wrapping the IDs in an object that has a values field, but your endpoint is expecting a plain array.

Instead of wrapping selectedRows like you do with deleteValues, just pass it through directly.

const handleDelete = async () => {
    await deleteSiteUser(selectedRows);
  };
Related