c# - 在 C# 中设置 AntiForgeryToken 以重定向到 HttpGet 方法
问题描述
我想使用 [ValidateAntiForgeryToken] 属性在我的 web 应用程序中检查 CSRF。问题是,我有一个更改数据的 GET 方法,所以它实际上应该是一个 POST。但是除了在相应的表单中提交到这个action方法之外,还有多个重定向到这个方法,所以我不能把它改成POST方法。据我所知, [ValidateAntiForgeryToken] 不适用于 GET 方法。是否有另一种方法来验证 GET 方法或在代码中重定向到 POST 方法而不使用表单?
我的操作方法如下所示:
public ActionResult SomeAction(SomeModel model)
{
// changes are made in database!!
return View("View", model);
}
并且此操作方法正在从另一个操作方法重定向到:
public ActionResult SomeOtherAction()
{
return RedirectToAction("SomeAction", "Controller");
}
我想将第一个操作更改为:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SomeAction(SomeModel model)
{
// changes are made in database!!
return View("View", model);
}
并在相应视图中添加@Html.AntiForgeryToken。但是,第二个动作中的重定向将不再起作用。有谁知道摆脱这种情况的方法?
解决方案
您可以返回 someAction 方法...
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
[ValidateAntiForgeryToken]
public ActionResult SomeOtherAction()
{
return SomeAction();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SomeAction()
{
return View("SomeAction");
}
}
索引.cshtml
@using (Html.BeginForm("SomeOtherAction", "Home", FormMethod.Get))
{
@Html.AntiForgeryToken();
<button type="submit">Click Me</button>
}
推荐阅读
- javascript - 如果没有输入焦点,则粘贴到默认文本区域
- python - 将列表推导与 for 循环和多个 if 语句一起使用
- python - 如何通过 Windows 上的 Python 子进程一次运行多个 shell 命令?
- python - Django过滤器:自定义组字段的多对多特定字段
- python - 使 Seaborn Distplot 和 Barplot 的颜色相同
- python - 我们如何在 PyTorch 中将线性层的输出提供给 Conv2D?
- swift - Swift Cocoa 通过 PHP 向应用发送通知
- ios - 选择搜索栏导致表格视图和搜索栏消失
- scala - Scala 测试错误:值 / 不是 sbt.Configuration 的成员
- sql - SQL 使用新列创建视图以保存来自 DateDiff 的值