【问题标题】:Multiple ActionFilterAttribute order of execution assured?多个 ActionFilterAttribute 的执行顺序有保证吗?
【发布时间】:2014-09-09 18:32:55
【问题描述】:

我刚刚研究了 ActionFilters,它们非常有用。现在,我尝试使用多个装饰方法,以分离逻辑。我认为这会很有用。

这里有一个示例方法

[Common.PortalSecurity.Login]
[Common.PortalSecurity.UserRole]
public HttpResponseMessage GetAll(string sessionToken)
{
    return new HttpResponseMessage();
}

这可以正常工作,但Login 必须在UserRole 之前执行。

每次请求都会100%遵守执行顺序吗?

这个blog post 似乎说它应该可以工作。

有什么想法吗?

【问题讨论】:

  • 以下是您如何执行此操作的示例:stackoverflow.com/questions/21628467/…
  • @KiranChalla 谢谢。您能否举例说明如何使用该解决方案装饰控制器方法?
  • @KiranChalla 没关系,有没有工作:) 编辑了我的答案。
  • 您应该使用身份验证或授权过滤器来确保登录安全,这些过滤器在操作过滤器之前执行。

标签: c# .net asp.net-web-api action-filter


【解决方案1】:

MVC5 中,您从 ActionFilter 继承并在自定义属性中指示顺序(使用 ActionFilter 的 Order 属性),如下所示:

[Common.PortalSecurity.Login(Order=1)]
[Common.PortalSecurity.UserRole(Order=2)]  
public HttpResponseMessage GetAll(string sessionToken)
{
    return new HttpResponseMessage();
}

您可以通过以下方式获取更多信息:https://msdn.microsoft.com/en-us/library/system.web.mvc.filterattribute.order(v=vs.118).aspx

【讨论】:

    【解决方案2】:

    我上面提出的解决方案是这样工作的:

    您的自定义属性必须继承:

    public class LoginAttribute : ActionFilterWithOrderAttribute
    {
    
    }
    
    public class UserRoleAttribute : ActionFilterWithOrderAttribute
    {
    
    }
    

    并且想要使用它的方法应该被修饰为:

    [Common.PortalSecurity.Login(Order=1)]
    [Common.PortalSecurity.UserRole(Order=2)]  
    public HttpResponseMessage GetAll(string sessionToken)
    {
        return new HttpResponseMessage();
    }
    

    【讨论】:

    • 这已经改变了吗?我只能声明 ActionFilterAttribute 而不是 ActionFilterWithOrderAttribute 虽然我可以使用 Order=1
    • 是的,我的解决方案使用它。你到底是什么问题?
    • Visual Studio 2013 只是不允许我使用ActionFilterWithOrderAttribute(尽管也许我做错了什么)。似乎只用ActionFilterAttribute 就可以正确应用订单,所以你的解决方案救了我!
    • @Aarmora 好吧,我使用的是 VS2010 和 .NET/MVC 4,所以如果您使用不同的版本,它可能会有所不同。我认为 MVC5 在没有该修复的情况下具有正确的排序。
    • 我在这里找到了此答案中描述的 ActionFilterWithOrderAttribute 的实现stackoverflow.com/questions/21628467/…
    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2017-03-10
    • 2021-03-07
    • 1970-01-01
    • 2016-05-02
    • 2014-07-22
    相关资源
    最近更新 更多