The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

asp.net Mvc-4asp.net Membership

asp.net Mvc-4 Problem Overview


I am using Membership.create user function, then the following error is occurring,

> The required anti-forgery form field "__RequestVerificationToken" is > not present

How can I fix this?

asp.net Mvc-4 Solutions


Solution 1 - asp.net Mvc-4

You have [ValidateAntiForgeryToken] attribute before your action. You also should add @Html.AntiForgeryToken() in your form.

Solution 2 - asp.net Mvc-4

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.

Solution 3 - asp.net Mvc-4

Like this:

The Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MethodName(FormCollection formCollection)
{
     ...
     Code Block
     ...
}

The View:

@using(Html.BeginForm())
{
     @Html.AntiForgeryToken()
     <input name="..." type="text" />
     // rest
}

Solution 4 - asp.net Mvc-4

Also make sure avoid not use [ValidateAntiForgeryToken] under [HttpGet].

  [HttpGet]
  public ActionResult MethodName()
  {
  ..
  }

Solution 5 - asp.net Mvc-4

You will receive the error even when Cookies are not enabled.

Solution 6 - asp.net Mvc-4

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.

Solution 7 - asp.net Mvc-4

Another possibility for those of us uploading files as part of the request. If the content length exceeds <httpRuntime maxRequestLength="size in kilo bytes" /> and you're using request verification tokens, the browser displays the 'The required anti-forgery form field "__RequestVerificationToken" is not present' message instead of the request length exceeded message.

Setting maxRequestLength to a value large enough to cater for the request cures the immediate issue - though I'll admit it's not a proper solution (we want the user to know the true problem of file size, not that of request verification tokens missing).

Solution 8 - asp.net Mvc-4

In my case, I had this javascript on the form submit:

$('form').submit(function () {
    $('input').prop('disabled', true);
});

This was removing the hidden RequestVerificationToken from the form being submitted. I changed that to:

$('form').submit(function () {
    $('input[type=submit]').prop('disabled', true);
    $('input[type=text]').prop('readonly', true);
    $('input[type=password]').prop('readonly', true);
});

... and it worked fine.

Solution 9 - asp.net Mvc-4

Make sure in your controller that you have your http attribute like:

[HttpPost]

also add the attribute in the controller:

[ValidateAntiForgeryToken]

In your form on your view you have to write:

@Html.AntiForgeryToken();

I had Html.AntiForgeryToken(); without the @ sign while it was in a code block, it didn't give an error in Razor but did at runtime. Make sure you look at the @ sign of @Html.Ant.. if it is missing or not

Solution 10 - asp.net Mvc-4

In my case it was due to adding requireSSL=true to httpcookies in webconfig which made the AntiForgeryToken stop working. Example:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true"/>
</system.web>

To make both requireSSL=true and @Html.AntiForgeryToken() work I added this line inside the Application_BeginRequest in Global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
  {
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
  }

Solution 11 - asp.net Mvc-4

If anyone experiences the error for the same reason why I experience it, here's my solution:

if you had Html.AntiForgeryToken();

change it to @Html.AntiForgeryToken()

Solution 12 - asp.net Mvc-4

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:

enter image description here

Solution 13 - asp.net Mvc-4

In my case incorrect domain in web.config for cookies was the reason:

<httpCookies domain=".wrong.domain.com" />

Solution 14 - asp.net Mvc-4

All the other answers in here are also valid, but if none of them solve the issue it is also worth checking that the actual headers are being passed to the server.

For example, in a load balanced environment behind nginx, the default configuration is to strip out the __RequestVerificationToken header before passing the request on to the server, see: https://stackoverflow.com/questions/23231063/simple-nginx-reverse-proxy-seems-to-strip-some-headers

Solution 15 - asp.net Mvc-4

In my EPiServer solution on several controllers there was a ContentOutputCache attribute on the Index action which accepted HttpGet. Each view for those actions contained a form which was posting to a HttpPost action to the same controller or to a different one. As soon as I removed that attribute from all of those Index actions problem was gone.

Solution 16 - asp.net Mvc-4

i'd like to share mine, i have been following this [anti forgerytoken tutorial][1] using asp.net mvc 4 with angularjs, but it throws an exception everytime i request using $http.post and i figured out the solution is just add ['X-Requested-With': 'XMLHttpRequest'][2] to the headers of $http.post, because it seems like the (filterContext.HttpContext.Request.IsAjaxRequest()) does not recognize it as ajax and here is my example code.

App.js

var headers = { 'X-Requested-With': 'XMLHttpRequest', 'RequestVerificationToken': $scope.token, 'Content-Type': 'application/json; charset=utf-8;' };

$http({ method: 'POST', url: baseURL + 'Save/User', data: JSON.stringify($scope.formData), headers: headers }).then(function (values) { alert(values.data); }).catch(function (err) { console.log(err.data); });


SaveController

[HttpPost] [MyValidateAntiForgeryToken] public ActionResult User(UserModel usermodel) { .... [1]: http://techbrij.com/angularjs-antiforgerytoken-asp-net-mvc [2]: https://stackoverflow.com/questions/33148695/identify-angular-js-ajax-calls-in-asp-net-mvc-code

Solution 17 - asp.net Mvc-4

Because this comes up with the first search of this:

I had this issue only in Internet Explorer and couldnt figure out the what the issue was. Long story short it was not saving the cookie portion of the Token because our (sub)domain had an underscore in it. Worked in Chrome but IE/Edge didnt not like it.

Solution 18 - asp.net Mvc-4

Sometimes you are writing a form action method with a result list. In this case, you cannot work with one action method. So you have to have two action methods with the same name. One with [HttpGet] and another with [HttpPost] attribute.

In your [HttpPost] action method, set [ValidateAntiForgeryToken] attribute and also put @Html.AntiForgeryToken() in your html form.

Solution 19 - asp.net Mvc-4

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();

Example

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)
{
    ...
}

Solution 20 - asp.net Mvc-4

I have solved it this way

[AttributeUsage(AttributeTargets.Method)]
public class ExcludeFromAntiForgeryValidationAttribute : Attribute{
}

and place System.Web.Helpers.AntiForgery.Validate(cookie != null ? cookie.Value : null, formToken) in if condition

bool shouldValidate =!filterContext.ActionDescriptor.GetCustomAttributes(typeof(ExcludeFromAntiForgeryValidationAttribute), true).Any();
if (shouldValidate){
    System.Web.Helpers.AntiForgery.Validate(cookie != null ? cookie.Value : null, formToken);
}

Solution 21 - asp.net Mvc-4

If you want to use [ValidateAntiForgeryToken] on a method you should just add @Html.AntiForgeryToken() to the form which is using the method mentioned.

If you have the method with the same name of the View(which has the form with @Html.AntiForgeryToken() ) then you should have two overloaded method in the controller.

Something like this:

First-> for the ActionResult for the view

[AllowAnonymous]
public ActionResult PasswordChange()
{
   PasswordChangeViewModel passwordChangeViewModel = new PasswordChangeViewModel();
   return View(passwordChangeViewModel);
}

Second-> for the HttpPost method

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult PasswordChange(PasswordChangeViewModel passwordChangeViewModel)
{
   //some code
} 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHemant SoniView Question on Stackoverflow
Solution 1 - asp.net Mvc-4webdeveloperView Answer on Stackoverflow
Solution 2 - asp.net Mvc-4Justin SkilesView Answer on Stackoverflow
Solution 3 - asp.net Mvc-4Subrata SarkarView Answer on Stackoverflow
Solution 4 - asp.net Mvc-4Haiping FanView Answer on Stackoverflow
Solution 5 - asp.net Mvc-4VijaychandarView Answer on Stackoverflow
Solution 6 - asp.net Mvc-4RomanView Answer on Stackoverflow
Solution 7 - asp.net Mvc-4GeoffMView Answer on Stackoverflow
Solution 8 - asp.net Mvc-4SeanView Answer on Stackoverflow
Solution 9 - asp.net Mvc-4juFoView Answer on Stackoverflow
Solution 10 - asp.net Mvc-4Ege BayrakView Answer on Stackoverflow
Solution 11 - asp.net Mvc-4WinnifredView Answer on Stackoverflow
Solution 12 - asp.net Mvc-4OgglasView Answer on Stackoverflow
Solution 13 - asp.net Mvc-4Michael LogutovView Answer on Stackoverflow
Solution 14 - asp.net Mvc-4DougView Answer on Stackoverflow
Solution 15 - asp.net Mvc-4Goran SnepergerView Answer on Stackoverflow
Solution 16 - asp.net Mvc-4Ran LorchView Answer on Stackoverflow
Solution 17 - asp.net Mvc-4kevhann80View Answer on Stackoverflow
Solution 18 - asp.net Mvc-4Masoud DarvishianView Answer on Stackoverflow
Solution 19 - asp.net Mvc-4demoncodemonkeyView Answer on Stackoverflow
Solution 20 - asp.net Mvc-4ilidiocnView Answer on Stackoverflow
Solution 21 - asp.net Mvc-4RoronoaZoro04View Answer on Stackoverflow