Search code examples
c#axiosjsx

Posting parameters to a C# endpoint via axios in React


I am trying to send parameters to a 'Post' endpoint but cannot hit the endpoint unless the signature is blank. Otherwise (as in the example below) I get an "Unsupported Media Type" error in the console. I can see that the parameters are going through but how do I access them in the C# method? What signature do I use in the method to have access to these values?

jsx:

  axios({
  method: 'post',
  url: '/cookie',
  data: JSON.stringify({ name: 'John', desc: 'Man' }),
  dataType: 'json'
  });

c#:

[ApiController]
[Route("[controller]")]
public class CookieController : ControllerBase
{
  [HttpPost(Name = "")]
   public void Post([FromBody] string data)
   {
    ... 
   }
}

Solution

  • jsx:

      axios({
      method: 'post',
      url: '/cookie',
      headers: { 'Content-Type': 'application/json' },
      data: JSON.stringify({ name: 'John', desc: 'Man' }),
      dataType: 'json'
      });
    

    The Javascript sends JSON data and the C# expects it as a DTO I called "CookieData" to suit the route:

    c#:

    [ApiController]
    [Route("[controller]")]
    public class CookieController : ControllerBase
    {
        public class CookieData
        {
            public string Name { get; set; }
            public string Desc { get; set; }
        }
         
        [HttpPost(Name = "")]
        public void Post([FromBody] CookieData data)
        {