How to use Ajax with AntiForgeryToken?

2

Follow the code:

//AntiForgeryToken
function gettoken() {
    var token = '@Html.AntiForgeryToken()';
    token = $(token).val();
    return token;
}

Ajax and formData:

var formData = new FormData();
var file = document.getElementById("imageFile").files[0];
var file1 = document.getElementById("coverFile").files[0];

$.ajax({
    cache: false,
    type: "POST",
    url: 'ação controller',
    data: {formData, gettoken}, <- como fazer aqui
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function (response) {
        if (response) {

        }
    }
    ,
    error: function (request, status, error)
    {
        alert('Error')
    }
});

PartialView:

<form id="myform">
    <div class="modal-body">

      Campos...

    </div>
    <input type="submit" class="btn btn-success" value="Criar" />
</form>

How to make AntiForgeryToken via Ajax to protect against counterfeiting? Any solution?

    
asked by anonymous 13.01.2017 / 01:31

1 answer

3

You will need to capture the value of the token before sending, this way

var form = $('#Id-do-Formulario'); //Tanto faz a forma de capturar
var token = $('input[name="__RequestVerificationToken"]', form).val();

Example

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<div id="id-da-div" data-url="@Url.Action("Index", "Home")">
    Ajax com ValidateAntiForgeryToken
</div>

<script type="text/javascript">
    $('#id-da-div').submit(function () {
        var form = $('#__AjaxAntiForgeryForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: { 
                __RequestVerificationToken: token, 
                formData: dadosParaEnviar 
            },
            success: function (result) {

            }
        });
        return false;
    });
</script>

Or, you can can capture the value with a function

<script type="text/javascript">
    function gettoken() {
        var token = '@Html.AntiForgeryToken()';
        token = $(token).val();
        return token;
    }
</script>

And use it as well

//ajax
data: {
    __RequestVerificationToken: gettoken(),
    formData: dados
},
    
13.01.2017 / 02:08