如何将MVC AntiForgeryToken与部分视图一起使用 [英] How to use MVC AntiForgeryToken with partial views

查看:72
本文介绍了如何将MVC AntiForgeryToken与部分视图一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个表单/视图,将根据用户响应显示一个或多个部分视图。我需要在哪里放置AntiForgeryToken?在父视图中?在局部视图?两个?



目前,我在部分视图中有它,但我们偶尔会收到错误:



类型:System.Web.Mvc.HttpAntiForgeryException

消息:未提供所需的防伪令牌或无效。



该错误仅在生产中报告,我们无法在开发人员机器上重现(典型值)。



我的理论是,当多个部分视图表示不匹配时发生令牌并报告错误。我的想法是将令牌移动到主/父视图。



我是否在正确的轨道上?任何人都必须处理类似的事情?

If I have a form/view that will display 1 or more partial views based on user responses. Where do I need to place the AntiForgeryToken? In the parent view? In the partial views? Both?

Currently, I have it in the partial views, but we are occasionally getting an error:

Type:System.Web.Mvc.HttpAntiForgeryException
Message:A required anti-forgery token was not supplied or was invalid.

The error is reported in production only, we are unable to reproduce it on developer machines (typical).

My theory is that when multiple partial views are represented a mismatch of tokens occurs and the error is reported. My thinking is to move the token to the main/parent view.

Am I on the right track? Anybody had to deal with something similar?

推荐答案

在你的视图中(假设剃刀),在表单中使用ValidateAntiForgeryToken的HTML帮助:



In your View(assuming razor), use the HTML helper for ValidateAntiForgeryToken inside the form:

@using (Html.BeginForm()) {
   @Html.ValidationSummary(true)
   @Html.AntiForgeryToken()
   <fieldset>
       </fieldset>







然后在控制器操作的HttpPost方法中,用ValidateAntiForgeryToken属性装饰它:






Then in the HttpPost method for the controller action, decorate it with the ValidateAntiForgeryToken attribute:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ModelType modelObj)
{
    if (ModelState.IsValid)
    {
        ///
    }

    return View(modelObj);
}


这篇关于如何将MVC AntiForgeryToken与部分视图一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆