0
votes

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....//
}
2
In your form in view. try to add this @using(Html.BeginForm("UserLogin","User", FormMethod.Post)) to make sure it redirects to post action of your controllerCybercop

2 Answers

1
votes

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
1
votes

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.