如何设置全局ValidateAntiForgeryToken [英] How can I set the ValidateAntiForgeryToken globally

查看:357
本文介绍了如何设置全局ValidateAntiForgeryToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在第一次安全。

MVC的最佳实践reccomend到 [ValidateAntiForgeryToken] 属性添加到每个 [HttpPost] 操作。

MVC best practices reccomend to add the [ValidateAntiForgeryToken] attribute to each [HttpPost] action.

我怎样才能在应用程序的一个独特之处强制执行这个规则?

How can I enforce this rule in one unique point of the application?

推荐答案

该follwing类允许与FilterProvider做到这一点。

The follwing class allow to do this with a FilterProvider

public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
    List<Filter> result = new List<Filter>();

    string incomingVerb = controllerContext.HttpContext.Request.HttpMethod;

    if (String.Equals(incomingVerb, "POST", StringComparison.OrdinalIgnoreCase))
    {
        result.Add(new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null));
    }

    return result;
}

要使用上述类 global.asx 将此添加到 RegisterGlobalFilters 方法文件:

To use the above class add this to the RegisterGlobalFilters method in global.asx file:

...    
FilterProviders.Providers.Add(new AntiForgeryTokenFilterProvider ());
..

这样做,每个 [HttpPost] 将检查 Html.AntiForgeryToken()是在视图中。

这篇关于如何设置全局ValidateAntiForgeryToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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