Using XMLHttpRequest from Javascript to Call a .Net Core Api

Imagine you have the following API endpoint:

https://localhost:1234/doStuff

The controller method for this might look like this:

[HttpPost]
public IActionResult DoStuff([FromBody]Data data)

If, for example, you create the sample .Net Core React app, you’ll see it getting the data using a construct like this:

const response = await fetch('doStuff');

This works fine if you’re retrieving data, but if you want to send some data through to the endpoint body, XMLHttpRequest allows you to send data in the body like this:

const xhr = new XMLHttpRequest();

xhr.open('POST', 'doStuff')
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ 
  data1: this.state.data1,
  data2: this.state.data2
}));

Unsupported Media Type

If, in the above code, you were to use:

const xhr = new XMLHttpRequest();

xhr.open('POST', 'doStuff')
//xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ 
  data1: this.state.data1,
  data2: this.state.data2
}));

You would be sending form data through to the controller. The call would not work, and you would get the following error from F12:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"|c86a375c-41ba2fd85652022a."}

There are two ways around this: the first, you’ve seen above, you set the content type; but you can also change the controller method to look like this:

[HttpPost]
public IActionResult DoStuff([FromForm]Data data)

References

https://stackoverflow.com/questions/39519246/make-xmlhttprequest-post-using-json

https://attacomsian.com/blog/http-requests-xhr

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.