Adding AntiForgeryToken to a non-Ajax form

I found many examples demonstrating how to add an AntiForgeryToken call to Ajax for the POST send method. My need, as the name suggests, is to submit the NOT form via an Ajax call. Instead, I just use the jQuery submit() function.

What I have in the razor view file is as follows (Note: I use the html string literal because this particular DOM must be dynamically bound to a single element at a later point):

 var html = "<form id='exportPdfForm' action='" + exportUrl + "' method='post'>" + "<input type='hidden' id='exportContent'>" + "<input type='hidden' id='__RequestVerificationToken' value='@Html.AntiForgeryToken()'>" + "</form>"; 

And obviously, I am using the following jQuery to submit this form:

 $("#exportPdfForm").submit(); 

Also, using the DOM Explorer, I see that the AntiForgeryToken value is AntiForgeryToken correctly: enter image description here

However, when I actually submit the form, I still encounter the error The required anti-forgery form field "__RequestVerificationToken" is not present . I checked several other Q&A, but I can not find anything that could shed light on my problem.

Did I miss something obvious or did something wrong?

EDIT (solution)

Assigning the __RequestVerificationToken attribute to the name attribute will be fixed:

 <input type='hidden' name='__RequestVerificationToken' value='...'> 
+5
source share
1 answer

This one turns out to be one of those, "How I missed it ...?!" moments. Although the above approach is completely finished, the only problem is that the __RequestVerificationToken must belong to the name attribute instead of id , as in my original example. I tried posting my hotfix form and the problem now disappeared.

Obviously, this would not be a problem in the first place, if I could just use the expression <% Html.AntiForgeryToken(); %> <% Html.AntiForgeryToken(); %> , but this particular case required an unconventional approach for the reason that I mentioned in my initial post. So, I think this is what you need to see!

+3
source

Source: https://habr.com/ru/post/1209169/


All Articles