Search code examples
jqueryjsonasp.net-mvcaxiosantiforgerytoken

__RequestVerificationToken not sent correctly with axios 0.17.1 and MVC 3/4/5


I eliminated jQuery from the project in favor of axios, but when I try to validate the __RequestVerificationToken, the controller responds with:

The required anti-forgery form field "__RequestVerificationToken" is not present

I see that the data is sent in json format and with jquery as form data.

Is there any way for the Controller to detect the json format or do I need to serialize the data before sending it?

axios({
      url: '/api/controller/method',
      data: {
        __RequestVerificationToken,
        otherData
      },
      method: 'post'
    })

Solution

  • We add a config file for axios and add a plugin "qs" to stringify the query.

    import qs from 'qs'
    import axios from 'axios'
    import fd from '../FormDataBuilder'
    
    axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
    axios.defaults.paramsSerializer = p => qs.stringify(p, { allowDots: true })
    axios.defaults.transformRequest = [d => typeof d === 'object' ? d.formdata ? fd(d) : qs.stringify(d, { allowDots: true }) : d]
    
    export default axios
    

    The FormDataBuilder is a function for the case of "formdata" forms.

    Now the server receive the token correctly.