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>
}
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:
- Send __RequestVerificationToken with Fetch API and recieve with an [ValidateAntiForgeryToken] action (StackOverFlow)
- Include antiforgerytoken in ajax post ASP.NET MVC (StackOverFlow)
- Using the Fetch API (MDN Web Docs)