0

I am attempting to use the ValidateAntiForgeryToken to prevent cross site forgery on my application. Keep getting the error

the required anti-forgery form field __requestverificationtoken is not present

Been seeing a lot of chatter on this but I have been unable to come up with a solution.

The code:

in my Index.cshtml, setting the AntiForgeryToken:

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

in my ajax.utilities post method, setting the token:

var post = function (options, callbacks) {
    // set default POST options
    options.type = "POST";
    options.dataType = options.dataType !== undefined ? options.dataType : "json";
    options.contentType = options.contentType !== undefined ? options.contentType : "application/json; charset=utf-8";

    var form = $('#__AjaxAntiForgeryForm');
    var token = $('input[name="__RequestVerificationToken"]', form).val();

    return sendRequest(options, callbacks);
};

my jquery sets the header properly i.e. "X-Requested-With":

            if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
                headers[ "X-Requested-With" ] = "XMLHttpRequest";
            }

finally in my controller I designate the HttpPost and ValidateAntiForgery attributes:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public  ActionResult CreateComposite(string name, int compositeTypeId, int componentTypeId, DateTime inceptionDate)
    {           
        return DispatchCommandWithJsonReturn(new CompositeCommands.CreateComposite(name, compositeTypeId, componentTypeId, inceptionDate));
    }

I still get the error the required anti-forgery form field __requestverificationtoken is not present

Using MVC 5, I don't know if that is relevant

Any ideas what is wrong?

edit: I've seen this issue elsewhere on the site, tried to make edits suggested, to no avail.

iAmOren
  • 2,760
  • 2
  • 11
  • 23
ar12ig
  • 11
  • 3
  • Does this answer your question? [The required anti-forgery form field "\_\_RequestVerificationToken" is not present Error in user Registration](https://stackoverflow.com/questions/16102957/the-required-anti-forgery-form-field-requestverificationtoken-is-not-present) – Dani Sep 21 '20 at 13:13

1 Answers1

1

I know this is old, but in case someone is having a problem like mine, in my case the issue was in the tag of the form, I had to add enctype = "multipart/form-data", so when I add the __RequestVerificationToken value to my ajax call data it will work.

user2903753
  • 153
  • 2
  • 12