【问题标题】:Add an action filter dynamically to specific action method将动作过滤器动态添加到特定的动作方法
【发布时间】:2015-08-27 10:36:33
【问题描述】:

一个问题的几个故事

  • 我实现了一个类 (MyClass),它有一个超时回调的东西,它应该在响应发送到客户端后立即启动。我可以使用action filter 来完成此操作,但我不想明确使用action filter(因为用户方便)。当 MyClass 在 Action Method 主体中实例化时,请附加 Action Filter

  • 我遇到一种情况,需要在执行操作后触发函数委托(用于跟踪超时事件)。

  • 考虑一个类,该类旨在当实例在该action method 上启动时运行一些代码(在执行action method 之后)。

  • 我需要在一个特定的动作执行它的结果后执行一些代码(我有它的动作名称)。

我知道使用custom Action Filter 并实现它的OnActionExecuted 方法是可行的方法,但我想知道的是,如何在操作时附加action filter 动态正在执行。
我的意思是,如何在不订阅Global.asax 的情况下附加action filter,也不使用[MyCustomActionFilter]Action Method 上方指定它。


已编辑:

考虑我有以下课程:

public class MyClass
{
  public List<SomeDelegate> TimeoutCallbackFunction{get; set;}

  public MyClass()
  {
     // I want to attach action filter here.
     // user may forget to attach MyFilter filter to Action Method
     // So that it would be easier for users if this handled by MyClass Constructor.
     HttpContext.Current....... or something
  }
}

考虑我的动作过滤器是:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{      
    // Fetch newly added callback delegates from session.
    // Run them all.
}

所以在控制器中我有以下代码:

//I want following filter attach to be removed.
//[MyFilter]
public ActionResult MyAction()
{
   // This piece of code, should attach action method with 'MyFilter' filter
   // And dismiss user from nominate it above of 'MyAction' action method
   MyClass myObject=new MyClass();
}

顺便说一下,“用户”是指使用我的类并基于我的 dll 开发 mvc.asp 的人。


我的问题是:
1- 是否可以将action filter 附加到当前正在执行的操作?如果是,怎么办?
2-如果不可能,那么我还有什么其他选择可以在Result Executed之后运行一些代码?
3- 如果没有其他选择,那么人们在这种情况下会怎么做?是否有任何标准化的方式来触发计时器回调?

【问题讨论】:

    标签: c# asp.net-mvc actionfilterattribute


    【解决方案1】:

    也许操作过滤器不是解决您问题的好方法。但是,当您想要执行操作过滤器功能时,您是否考虑过在某处创建一个简单的标志并将其设置为 true?例如:

    在您的代码中设置标志:

    HttpContext.Current.Items["ExecuteMyActionFilter"] = true
    

    在您的操作过滤器中:

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if ((bool?) HttpContext.Current.Items["ExecuteMyActionFilter"] == true)
        {
            // Execute your code
        }
    }
    

    您可以使用静态变量、数据库或任何状态条件来检查您的操作是否需要执行。希望你明白了!

    【讨论】:

    • @Rzassar 仍然,答案是一样的。我没有看到更好的方法。
    • 问题是,我应该在哪里附加过滤器?我的意思是应该如何调用OnActionExecuted(而我想省略用户手动过滤注册)并将用户从这种复杂性中释放出来。我宁愿强迫用户在所需的操作方法上方调用 [MyFilter],也不愿强迫用户将标志调低或调高。
    • 顺便说一下,“用户”是指使用我的类并基于我的 dll 开发 mvc.asp 的人。
    • 伙计,你必须根据条件做一些事情,也许你不应该为你的问题使用动作过滤器。这是我的印象……
    • @Andrei M 你完全正确。另一方面,正如我提到的“如何附加一个动作过滤器而不在 Global.asax 中订阅它,也不使用 [MyCustomActionFilter] 在动作方法上方指定它”。我的意思是,如何在不需要静态注册的情况下实现action filter &gt;&gt;&gt; OnActionExecuted 之类的功能。现在!你觉得有没有另一种方法可以在响应发送给客户端之前执行一些代码?
    猜你喜欢
    • 2016-11-21
    • 2013-09-29
    • 2012-10-05
    • 2023-03-07
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    相关资源
    最近更新 更多