首页 > 解决方案 > 在 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。但是,第二个动作中的重定向将不再起作用。有谁知道摆脱这种情况的方法?

标签: c#redirecthttp-postcsrf

解决方案


您可以返回 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>
}

推荐阅读