asp.net-mvc - 如何在 MVC 的 Controller 级别使用 ValidateAntiForgeryToken?

标签 asp.net-mvc asp.net-core asp.net-core-mvc antiforgerytoken coreclr

我有 ASP.NET Core 应用程序。我一直在用ValidateAntiForgeryToken所有 POST 的属性 Action 方法到此为止。

现在我想使用 ValidateAntiForgeryToken在 Controller 级别,因此它可以同时处理 POSTGET方法。

下面是示例 Controller

[ValidateAntiForgeryToken]
public class SearchController : Controller
{
    public SearchController()
    {
    }

    [HttpGet]
    public IActionResult Index()
    {           
        return View();
    }      

    [HttpPost]
    public IActionResult Save(MyModel model)
    {

    }

}

当用户访问 URL http://localhost/search 时, 我不知道如何 Index Action 方法会收到伪造 token 吗?现在我收到错误 Bad Request因为请求中没有包含 token 。

最佳答案

来自 http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

防伪助手的局限性

It only works with POST requests, not GET requests. Arguably this isn’t a limitation, because under the normal HTTP conventions, you shouldn’t be using GET requests for anything other than read-only operations.



所以它在 Controller 级别没有用。

ASP.NET 核心
[ValidateAntiforgeryToken]对 Controller 有限制。

https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-2.1

ASP.NET Core doesn't support adding antiforgery tokens to GET requests automatically.


[AutoValidateAntiforgeryToken] 改进了 Controller 级支持

This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods:

  • GET
  • HEAD
  • OPTIONS
  • TRACE

关于asp.net-mvc - 如何在 MVC 的 Controller 级别使用 ValidateAntiForgeryToken?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41453856/

相关文章:

javascript - 单击按钮时将 Razor 变量作为函数参数发送

asp.net-mvc - ASP.NET MVC : Prevent user from editing certain fields on the model

c# - 如何获取 MVC Controller 中当前的 url 协议(protocol)?

c# - 使用 MVC Core 时将参数传递给 main 方法

asp.net - 是否有用于 SEO 的 Vanity URL 的开源 ASP.Net 插件/模块?

c# - 为什么 Asp.Net Core 身份验证方案是强制性的

asp.net-core - 脚手架MVC在继承IdentityDbContext时不加载ApplicationDbContext

c# - Visual Studio 在发布过程中使用 launchSettings.json 配置文件中定义的哪一个?

asp.net - 更新数据库失败 : "The index ' IX_Task_UserId' is dependent on column 'UserId' "

c# - 如何在 .Net Core 的 AuthorizeAttribute 类中访问 appsetting.json 参数