I am using Membership.create
user function, then the following error is occurring,
The required anti-forgery form field \"__RequestVerifi
You will receive the error even when Cookies are not enabled.
Got this error in Chrome with default login for ASP.NET with Individual User Accounts
.cshtml:
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
Solved by clearing site data for the site:
In my case I was getting this error while making an AJAX post, it turned out to be that the __RequestVerificationToken
value wasn't being passed across in the call. I had to manually find the value of this field and set this as a property on the data object that's sent to the endpoint.
i.e.
data.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
HTML
<form id="myForm">
@Html.AntiForgeryToken()
<!-- other input fields -->
<input type="submit" class="submitButton" value="Submit" />
</form>
Javascript
$(document).on('click', '#myForm .submitButton', function () {
var myData = { ... };
myData.__RequestVerificationToken = $('#myForm input[name="__RequestVerificationToken"]').val();
$.ajax({
type: 'POST',
url: myUrl,
data: myData,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType: 'json',
success: function (response) {
alert('Form submitted');
},
error: function (e) {
console.error('Error submitting form', e);
alert('Error submitting form');
},
});
return false; //prevent form reload
});
Controller
[HttpPost]
[Route("myUrl")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> MyUrlAsync(MyDto dto)
{
...
}
Another thing that can cause this (just ran into this) is the following: if you for some reason disable all your input fields in your form. it will disable the hidden input field that holds your verification token. when the form will be posted back the token value will be missing and will generate the error that it is missing. so what you need to do is to re-enable the input field that holds the verification token and all will be well.
In my case, I had this in my web.config:
<httpCookies requireSSL="true" />
But my project was set to not use SSL. Commenting out that line or setting up the project to always use SSL solved it.
Also make sure avoid not use [ValidateAntiForgeryToken] under [HttpGet].
[HttpGet]
public ActionResult MethodName()
{
..
}