Programmatically/Dynamically Exclude ActionFilter
I have an ActionFilterAttribute that uses OnActionExecuted to do some manipulation of the ViewModel after it has been generated by the Controller Action. In some cases (eg, if a condition is met, I just want to Redirect and don't care about the ViewModel) I don't want the ActionFilter to execute.
How can I programmatically, tell an ActionFilter to not execute?
Related is this post where you can decorate the Action to exclude an attribute that might be set in the GlobalFilterCollection (or set on the controller and exclude on the action): http://blogs.microsoft.co.il/oric/2011/10/28/exclude-a-filter/
The easiest way would be to simply add code to your ActionFilter to detect the condition and not execute the code if the condition is true.
However, if you don't want to alter the filter for some reason, you can use the FilterProvider technique in the link you provided. But, you would write the filter provider to detect the condition and exclude the filter.
The problem here is that you haven't told us what kind of condition you require, nor how you intend to identify which action it should apply to.
Just guessing here, but you could do something like this:
[MyAttribute]
public class HomeController : Controller
{
[ExcludeFilter(typeof(MyAttribute), typeof(MyFilterCondition)]
public ActionResult Index()
{
return View();
}
}
Then you would create a MyFilterCondition class that would be based on some interface you define so that it has a known contract.. such as IFilterCondition (you create this, it doesn't exist)
public interface IFilterCondition
{
bool Exclude();
}
public class MyFilterCondition : IFilterCondition
{
public bool Exclude()
{
// logic that determines whether to exclude the attribute
}
}
Then you would create you custom ExcludeFilterAttribute and ExcludeFilterProvider similar to your link, but you add the additional filter condition type to ExcludeFilterAttribute that is used to determine the condition in which to exclude the filter, and then add some additional logic to the Filter provider that uses reflection to get a new IFilterCondition instance based on that type and call the Exclude() method to determine if you want to exclude the filter or not.
However, this is all still very static and requires that you define at compile time which actions you want to filter, and which conditions you want to filter with. If you need more flexibility then you may wish to rethink using filters in the way you are using them, because they execute at a much higher level of the pipeline and it requires getting your hands much dirtier to tweak that.
链接地址: http://www.djcxy.com/p/74436.html上一篇: 从请求过滤器返回特定的操作结果