質問

In my SPA website i need to send antiforrgery token over to server by ajax. I use this article method:

http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-%28csrf%29-attacks

So in my layout.cshtml i have local function :

<script>
    @functions{
    public string TokenHeaderValue()
    {
        string cookieToken, formToken;
        AntiForgery.GetTokens(null, out cookieToken, out formToken);
        return cookieToken + ":" + formToken;                
    }
}
</script>

and i have separate js file named register.js where i call this function inside ajax:

   $.ajax({
                url: 'User/JsonRegister',
                type: "POST",
                data: d,
                headers: {
                    'RequestVerificationToken': '@TokenHeaderValue()'
                },
                success: function (result) {
                },
                error: function (result) {
                }
            });

the problem is that i never @TokenHeaderValue() is never called and i m keep getting this error:

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

How do i solve this problem?

役に立ちましたか?

解決 2

i add token to my data this way: which solves problem

 AddAntiForgeryToken = function (data) {
            data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
            return data;
        };

他のヒント

The problem is using server side helper function in the separate js file. If you need to have ajax call in the separate js file, set @TokenHeaderValue() value to a hidden field and read the value of hidden field in the js file.

Pass data in JSON format

$.ajax({
     type:"POST",
     datatype:"JSON",
     data:{d:d}, // Remaining code is same

});

And use [HttpPost] before method signature in controller because it a Post request.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top