javascriptaxiosasp.net-mvc-5

Calling MVC5 action using AXIOS and ValidateAntiForgeryToken


I am trying to call a controller method marked with [ValidateAntiForgeryToken] from my UI using Axios.

I have successfully called the same action by using jQuery ajax.

Working AJAX Code.

First I get the token from my form:

   var addAntiForgeryToken = function (data) {
            data.__RequestVerificationToken = $("[name='__RequestVerificationToken']").val();
            return data;
        };

and then I call my method:

  $.ajax({
        type: "POST",
        url: "http://localhost:40428/controller/action",
        data: addAntiForgeryToken({ }),
        success: function (response) {

        }
    });

The above successfully calls the following method in my controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Test_Get()
    {
        ViewBag.Search = true;
        return View("Index");
    }

What i have already tried with axios is the following:

    axios({
            method: 'post',
            url: 'http://localhost:40428/Meeting_Notes/Test_Get',
            data: addAntiForgeryToken({})
        });

I have also tried setting the headers manually but I still cannot get it to work.


Solution

  • After searching around for a bit I found a simple solution. First create the controller and decorate it with HttpPost and ValidateAntiForgeryToken

    [HttpPost]
    [ValidateAntiForgeryToken]
    public void Test_Axios(int id) { }
    

    Then before calling the controller using axios add the following interceptor for the headers. This will define the header as default for all axios api calls

    axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    

    then retreive the token

    var token = document.querySelector('token, input').getAttribute('value');
    

    then use the qs library to stringify the call with the token (Be careful! it's Qs and not qs!)

    var request = Qs.stringify({ id: 22, __RequestVerificationToken: token });
    

    if you don't wanna pass any parameters then you can just use the following

    var request = Qs.stringify({ __RequestVerificationToken: token });
    

    then just call the controller method

    axios({
         method: 'post',
         url: "/controller/Test_Axios",
         data: request 
    });
    

    And you are done! You can now start calling mvc 5 controller, decorated with the [ValidateAntiForgeryToken] attribute.