Reputation: 404
I have created a login form and some other controllers in mvc4. I put [ValidateAntiForgeryToken] on controllers and @Html.AntiForgeryToken() in each view. but after login when the page is redirected to another page it gives an error
The required anti-forgery form field "__RequestVerificationToken" is not present."
my sample controller is
[HttpPost, ActionName("UserLogin")]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult UserLogin(FormCollection collection)
{
string username = collection["txtUser"].ToString();
string password = collection["pwd"].ToString();
string Browser = HttpContext.Request.Browser.Browser;
if (db.Users.Any(u => u.Email == username && u.Password == password))
{
User usr = db.Users.Single(u => u.Email == username && u.Password == password);
return RedirectToAction("Details","User",usr.Id);
}
return HttpNotFound();
}
and view is
@using(Html.BeginForm("UserLogin","User")){
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
/// .......form elements....//
}
Upvotes: 0
Views: 3492
Reputation: 761
RedirectToAction causes the browser to make a GET
request to the specified action according to MSDN. Your AntiForgeryToken is only available when you POST a form. Therefore the action you redirect to can't expect an AntiForgeryToken
.
Upvotes: 1
Reputation: 25
I added If ModelState.IsValid Then
to the method. This caused the model to work correctly with validation.
@Using Html.BeginForm("request_a_quote", "Furniture_Assembly_Quote", FormMethod.Post, New With {.class = "form-horizontal", .role = "form"})
@Html.AntiForgeryToken()
@<text>
<div Class="row">
<div Class="col-md-6">
<hr />
@Html.ValidationSummary("", New With {.class = "text-danger"})
<HttpPost>
<AllowAnonymous>
<ValidateAntiForgeryToken>
Public Function Request_a_quote(model As RequestViewModel) As ActionResult
If ModelState.IsValid Then
End If
End Function
Upvotes: 1