Reputation: 3318
I have a form that looks like
@using(Html.BeginForm())
{
@Html.AntiForgeryToken()
<!-- Some form inputs -->
<div>@Html.ActionLink("LinkText", "MyAction")</div>
}
My Action is defined as follows:
[ValidateAntiForgeryToken}
public ActionResult MyAction()
{
return View();
}
When I click on the action link, I'm getting the error: The required anti-forgery form field "__RequestVerificationToken" is not present.
Upvotes: 0
Views: 2320
Reputation: 4443
[ValidateAntiForgeryToken]
is validated on POST
action, not with GET
. So, your code should look like this:
@using(Html.BeginForm())
{
@Html.AntiForgeryToken()
<!-- Some form inputs -->
<input type="submit" value="Submit" />
}
and your action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyAction()
{
return View();
}
Upvotes: 0
Reputation: 39807
An action link performs a GET
request to the server. During a GET
request, no form fields are passed, including the hidden field for the AntiForgeryToken. That is why you are getting the error. The AntiForgeryTokens only work when POSTing information back to your server and not for basic GET
request.
Here is the MSDN for the AntiForgeryToken helper. Note that is states:
Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.
In order to pass the AntiForgeryToken, you need to POST
/submit the form. Change the following and all should work as intended.
@using(Html.BeginForm("MyAction", "MyController"))
{
@Html.AntiForgeryToken()
<!-- Some form inputs -->
<div><input type="submit" value="MyText"/></div>
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyAction()
{
return View();
}
However, I wanted to point out that the above code changes breaks the Post-Redirect-Get pattern of MVC. Your return from a HttpPost ActionResult
should be return RedirectToAction("Something")
as opposed to a view.
Upvotes: 1