0

Trying to apply the C# Razor AntiForgeryToken to some Ajax calls in my app due to security audit recommendations and after trying to implement many of the solutions on the following stack question: include antiforgerytoken in ajax post ASP.NET MVC

I always get the same error, on the first time I call Html.AntiForgeryToke() it opens successfully, but then when opening a second Page or the same Page a second time Html.AntiForgeryToken() throws System.ObjectDisposedException: safe handle is closed

How can I add an AntiForgeryToken to every form/page, if the Html.AntiForgeryToken() method can only be called once?

Here's some sample of the current implementation (used this literally), lets call it the Index page, where I have the following hidden Form:

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

Where I have also a button/icon with the following JS function (changed method names and var names only)

$('#myIcon').click(function () {

    var form = $('#__AjaxAntiForgeryForm');
    var dataTosend = { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]', form).val() };

    myAjaxPostUtilFunc('@Url.Action("OpenAPopupAction", "MyControllerName")', dataTosend, function (data) {
        myReturnAction(data); //will open a popup with stuff

    }, { type: "POST", dataType: "html" });
});

Then navigating a 2nd time to my Index page throws exception.

EDIT (added mvc version in tags for clarity): Found a reference to a similar issue: mvc 6 generates antiforgerytoken only once The bug seems to be present on MVC 5 and 6 (and maybe core v1). Currently attempting the solutions on this other Post, will share if they work later.

Gotham Llianen
  • 471
  • 1
  • 6
  • 17

0 Answers0