質問

So I have a very simple form on my page which looks like this

@using(Html.BeginForm("SomeAction", "SomeController", FormMethod.Post))
{
    Html.AntiForgeryToken();

    // some other fields go here

    <input type="submit" value="DoStuff" />
}

and the action looks like this

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult SomeAction()
{
    // Do some stuff here and return
}

first of all, if I do not give the AntiForgeryToken method a salt parameter it does not generate any hidden field or anything like that containing a token, so clicking that submit button redirects to the error page, which says required anti forgery field is not present. Now, if I put any salt in there, for instance Username

Html.AntiForgeryToken(User.Identity.Name); // I Use FormsAuthentication

then the browser says, web page has a redirect loop. this is the first time I'm using AntiForgeryToken so I don't understand why this is happening. Can anyone help me out. Any help would be appriciated.

役に立ちましたか?

解決

The following Html extensions:

@Html.AntiForgeryToken()

Always generates a hidden field, even if no salt has been passed as a parameter. What is more the anti-CSRF capabilities of MVC actually depend on two tokens: one is a hidden form element, and the other is a cookie. So the Html.AntiForgeryToken() helper doesn't just return an HTML snippet. It also has a side effect of setting this cookie. So you need to make sure that cookies are enabled.

Btw any other overload of this method apart from the parameterless one is obsolete: http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.antiforgerytoken(v=vs.118).aspx

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top