Portada » Preguntas Frecuentes de .NET 6 » ¿Cómo enviar el AntiforgeryToken en una petición Ajax con .NET 6 MVC?

¿Cómo enviar el AntiforgeryToken en una petición Ajax con .NET 6 MVC?

La forma de implementar el envío del AntiforgeryToken en una petición AJAX de la manera más rápida, es indicar lo siguiente en tu vista donde vayas a hacer el submit del formulario:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Form" }))
{
    @Html.AntiForgeryToken()
    <button type="button" onclick="submitForm()">SUBMIT</button>
}

Si no sabes por qué el botón tiene type=»button» en vez de type=»submit» te lo explico en el artículo: ¿Cómo evitar reenviar el formulario al hacer un POST con Ajax?

Opción con JQuery

Luego usando JQuery podemos obtener este RequestVerificationToken del formulario:

const submitForm = () => $.post(`Controller/Action`,
    {
        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]', $('#Form')).val()
    })
    .done(() => console.log("exito"))
    .fail(() => console.log("error"));

Y en el Controller ya podemos poner el DataAnnotation [ValidateAntiForgeryToken] :

[HttpPost]
[ValidateAntiForgeryToken]
public void Action()
{

    // La lógica que consideres
}

Con esto en principio ya se realiza un envío adecuado del formulario con el AntiforgeryToken.

Opción con Vanilla Javascript

Otra opción es utilizando el Fetch API de Javascript y añadiendo headers para identificar el AntiforgeryToken ahí. Lo primero añadimos a la configuración (Program.cs) lo siguiente:

builder.Services.AddAntiforgery(x => x.HeaderName = "X-ANTI-FORGERY-TOKEN");

Hecho esto, podemos añadir el token con Javascript:

const HideAllNotifications = () => {
    let notificationForm = document.getElementById("Form");
    let rvt = notificationForm.querySelector("input[name='__RequestVerificationToken']").value;
    fetch(`Notifications/CloseAllNotifications`,
        {
            method: "POST",
            mode: "cors",
            headers: {
                "X-ANTI-FORGERY-TOKEN": rvt
            }
        })
}

Y como antes, ya podemos añadir el DataAnnotation de [ValidateAntiForgeryToken] en tu controlador.

Referencias: