【发布时间】:2018-04-18 19:59:24
【问题描述】:
在 ASP.NET Core 2.0 应用程序中,我试图在执行控制器的变体之前执行全局过滤器的 OnActionExecuting。预期的行为是我可以在全局之前准备一些东西并将结果值传递给控制器。但是,当前的行为是设计颠倒了执行顺序。
文档告诉我default order of execution:
从 Controller 基类继承的每个控制器都包含 OnActionExecuting 和 OnActionExecuted 方法。这些方法包装了针对给定操作运行的过滤器:在任何过滤器之前调用 OnActionExecuting,在所有过滤器之后调用 OnActionExecuted。
这使我解释为控制器的OnActionExecuting 在任何过滤器之前执行。说得通。但是文档还通过实现IOrderedFilter 声明the default order can be overridden。
我在过滤器中实现这一点的尝试是这样的:
public class FooActionFilter : IActionFilter, IOrderedFilter
{
// Setting the order to 0, using IOrderedFilter, to attempt executing
// this filter *before* the BaseController's OnActionExecuting.
public int Order => 0;
public void OnActionExecuting(ActionExecutingContext context)
{
// removed logic for brevity
var foo = "bar";
// Pass the extracted value back to the controller
context.RouteData.Values.Add("foo", foo);
}
}
此过滤器在启动时注册为:
services.AddMvc(options => options.Filters.Add(new FooActionFilter()));
最后,我的 BaseController 看起来像下面的示例。这最好地解释了我想要实现的目标:
public class BaseController : Controller
{
public override void OnActionExecuting(ActionExecutingContext context)
{
// The problem: this gets executed *before* the global filter.
// I actually want the FooActionFilter to prepare this value for me.
var foo = context.RouteData.Values.GetValueOrDefault("foo").ToString();
}
}
将Order 设置为 0,甚至是像 -1 这样的非零值,似乎对执行顺序没有任何影响。
我的问题:我可以做些什么来让我的全局过滤器执行OnActionExecuting之前(基本)控制器的OnActionExecuting?
【问题讨论】:
-
根据文档,我想说
Order属性只能用于覆盖过滤器的默认顺序,并且该属性不会影响控制器方法和过滤器的顺序。跨度>
标签: c# asp.net-core .net-core action-filter