How can I supply an AntiForgeryToken when posting

2019-01-02 18:04发布

I am using the code as below of this post:

First I will fill an array variable with the correct values for the controller action.

Using the code below I think it should be very straightforward by just adding the following line to the JavaScript code:

data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();

The <%= Html.AntiForgeryToken() %> is at its right place, and the action has a [ValidateAntiForgeryToken]

But my controller action keeps saying: "Invalid forgery token"

What am I doing wrong here?

Code

data["fiscalyear"] = fiscalyear;
data["subgeography"] = $(list).parent().find('input[name=subGeography]').val();
data["territories"] = new Array();

$(items).each(function() {
    data["territories"].push($(this).find('input[name=territory]').val());
});

    if (url != null) {
        $.ajax(
        {
            dataType: 'JSON',
            contentType: 'application/json; charset=utf-8',
            url: url,
            type: 'POST',
            context: document.body,
            data: JSON.stringify(data),
            success: function() { refresh(); }
        });
    }

13条回答
不流泪的眼
2楼-- · 2019-01-02 18:43

Unfortunately for me, the other answers rely on some request formatting handled by jquery, and none of them worked when setting the payload directly. (To be fair, putting it in the header would have worked, but I did not want to go that route.)

To accomplish this in the beforeSend function, the following works. $.params() transforms the object into the standard form / url-encoded format.

I had tried all sorts of variations of stringifying json with the token and none of them worked.

$.ajax({
...other params...,
beforeSend: function(jqXHR, settings){

    var token = ''; //get token

    data = {
        '__RequestVerificationToken' : token,
        'otherData': 'value'
     }; 
    settings.data = $.param(data);
    }
});

```

查看更多
登录 后发表回答