我可以使用没有 AcceptVerbs 标签的 AntiForgeryToken 吗?
我想使用 AntiForgeryToken 函数,但 AcceptVerbs 帖子不适用。我收到防伪错误。有没有办法不用 post 方法来做到这一点?
public ActionResult Page1(string data)
{ //code with view that includes link to Edit }
public ActionResult Page2(string data)
{ //code with view that includes link to Edit }
public ActionResult Edit(string pageName)
{ //execution then redirect to Page1/Page2 }
I would like to use the AntiForgeryToken function but the AcceptVerbs post does not apply. I am getting the anti forgery error. Is there a way to do this without the post method?
public ActionResult Page1(string data)
{ //code with view that includes link to Edit }
public ActionResult Page2(string data)
{ //code with view that includes link to Edit }
public ActionResult Edit(string pageName)
{ //execution then redirect to Page1/Page2 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
防伪令牌通过 cookie 和表单中的隐藏输入字段发挥作用。它们都拥有相同的加密值。当控制器处理用
[ValidateAntiForgeryToken]
修饰的操作时,它会检查 cookie 中的值和隐藏的输入字段是否匹配。如果他们不这样做,你就会得到一个很好的例外。您可以使用这样的代码
View:
Controller:
但生成的表单会获得一个
method="post"
属性。在控制器端,您不需要指定[AcceptVerbs(HttpVerbs.Post)]
。因此,您的问题的答案是您可以使用 AntiForgeryToken,而不使用 AcceptVerbs 属性。您只需要在表单中使用 POST 方法即可。要继续该示例,如果您在操作上指定
[AcceptVerbs(HttpVerbs.Get)]
并指定Html.BeginForm("DoSomething", "Default", FormMethod.Get)
,该示例将不起作用,因为 GET 请求不包含 cookie,只有隐藏的输入值被编码在查询字符串中。The anti forgery token works by a cookie and a hidden input field in the form. They both hold the same encrypted value. When the controller handles an action decorated with
[ValidateAntiForgeryToken]
it checks if the values in the cookie and the hidden input field match. If they don't - you get a nice exception.You can use code like this
View:
Controller:
But then the form generated gets an
method="post"
attribute. On the controller side you don't need to specify[AcceptVerbs(HttpVerbs.Post)]
. So the answer to your question is that you can use AntiForgeryToken without the AcceptVerbs attribute. You just need to use the POST method in the form.To continue with the sample, if you specify
[AcceptVerbs(HttpVerbs.Get)]
on the action andHtml.BeginForm("DoSomething", "Default", FormMethod.Get)
, the example won't work, because the GET request does not contain the cookie only the hidden input value gets encoded in the query string.