【问题标题】:How can I set the ValidateAntiForgeryToken globally如何全局设置 ValidateAntiForgeryToken
【发布时间】:2011-07-09 23:01:07
【问题描述】:

首先是安全性。

MVC 最佳实践建议将[ValidateAntiForgeryToken] 属性添加到每个[HttpPost] 操作。

如何在应用程序的一个独特点强制执行此规则?

【问题讨论】:

    标签: asp.net-mvc model-view-controller asp.net-mvc-3 action-filter


    【解决方案1】:

    以下类允许使用 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 方法中:

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

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

    【讨论】:

    • 您的过滤器提供程序是否继承自任何基类?
    • 该代码将为应用程序的每个请求创建一个列表。可以通过使用yield来改进:yield return new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 2018-11-03
    • 2015-01-09
    • 2011-02-11
    • 2017-12-06
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多