ASP.NET Core MVC WebApi中如何定义路由方法前置执行方法?
解决方案
针对你的需求,最简便的两种实现方式如下:
方法一:重写控制器的OnActionExecuting方法
ControllerBase自带虚方法OnActionExecuting,会在每个Action方法执行前自动调用,完全匹配你的需求,且无需额外创建类:
public class ExampleController : ControllerBase { private static int i; private void funcToCall() { i++; } // 重写此方法,在Action执行前触发 public override void OnActionExecuting(ActionExecutingContext context) { // 若仅需针对Ping方法执行,可添加Action名称判断 if (context.ActionDescriptor.DisplayName.Contains(".Ping")) { funcToCall(); } base.OnActionExecuting(context); } [HttpGet] public IActionResult Ping() { return Ok("Pong"); } }
- 优势:无需额外代码,直接利用控制器原生生命周期方法,
funcToCall可保持私有访问权限。 - 适用场景:仅需在当前控制器的特定/所有Action执行前触发逻辑。
方法二:自定义Action Filter(复用性更高)
如果后续需要在多个控制器/Action中复用该逻辑,可创建自定义Action Filter:
- 定义Filter类:
public class PreActionCallFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { // 若要调用控制器内的私有方法,需将其改为public/internal,或直接将逻辑移至Filter中 if (context.Controller is ExampleController controller) { controller.funcToCall(); // 需修改funcToCall为public } // 若无需依赖控制器,可直接将逻辑写在这里 // i++; base.OnActionExecuting(context); } }
- 在目标Action上标记Filter:
[HttpGet] [PreActionCallFilter] public IActionResult Ping() { return Ok("Pong"); }
- 优势:逻辑可复用,支持全局注册(在
Program.cs中配置后,所有Action自动生效)。 - 注意:若要调用控制器的私有方法,需修改其访问修饰符为
public或internal,更推荐将逻辑直接封装在Filter中以实现解耦。
内容的提问来源于stack exchange,提问作者Oskar Wiszowaty
相关产品推荐
相关产品推荐

