确保每个控制器方法有ValidateAntiForgeryToken属性? [英] make sure each controller method has a ValidateAntiForgeryToken attribute?

查看:777
本文介绍了确保每个控制器方法有ValidateAntiForgeryToken属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法来集中执法的每一个动作方法必须有一个ValidateAntiForgeryToken属性?我想它将不得不通过延长其中的路由类来完成。

Is there any way to centralize enforcement that every action method must have a "ValidateAntiForgeryToken" attribute? I'm thinking it would have to be done by extending one the "routing" classes.

编辑:或做也许在应用程序启动一些反思

Or maybe do some reflection at application startup?

推荐答案

是的。您可以通过创建自己的BaseController继承了MVC控制器做到这一点,重载OnAuthorization()。你要强制执行之前,以确保它是一个POST事件:

Yes. You can do this by creating your own BaseController that inherits the Mvc Controller, and overloads the OnAuthorization(). You want to make sure it is a POST event before enforcing it:

public abstract class MyBaseController : Controller
{
  protected override void OnAuthorization(AuthorizationContext filterContext)
  {
    //enforce anti-forgery stuff for HttpVerbs.Post
    if (String.Compare(filterContext.HttpContext.Request.HttpMethod,
          System.Net.WebRequestMethods.Http.Post, true) == 0)
    {
      var forgery = new ValidateAntiForgeryTokenAttribute();
      forgery.OnAuthorization(filterContext);
    }
    base.OnAuthorization(filterContext);
  }
}

一旦你有一个,确保所有控制器,从这个MyBaseController(或者无论你怎么称呼它)继承。或者,如果你用相同的code喜欢你可以做到这一点每个控制器。

Once you have that, make sure all of your controllers inherit from this MyBaseController (or whatever you call it). Or you can do it on each Controller if you like with the same code.

这篇关于确保每个控制器方法有ValidateAntiForgeryToken属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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