Asp.net mvc 意外调用的OnActionExecuted
我有以下行动方法:Asp.net mvc 意外调用的OnActionExecuted,asp.net-mvc,Asp.net Mvc,我有以下行动方法: public class HomeController : Controller { [ProfileAction] [CustomAction] public string FilterTest() { //Does not get executed return "This is t
public class HomeController : Controller
{
[ProfileAction]
[CustomAction]
public string FilterTest()
{
//Does not get executed
return "This is the FilterTest action";
}
}
以下是过滤器的代码:
public class CustomActionAttribute : FilterAttribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
//This is executed first
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
//This is executed third
}
}
public class ProfileActionAttribute : FilterAttribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
//This is executed second
filterContext.Result = new HttpNotFoundResult();
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
//this does not execute
}
}
根据OnActionExecuted(),
在控制器动作执行后执行
操作方法FilterTest()
从未被调用,因为我在ProfileActionAttribute.OnActionExecuting()
中设置了Result属性。
如果action方法从未被调用,为什么CustomActionAttribute.OnActionExecuted()会被调用?我认为这是因为确实调用了action。客户机请求与操作方法关联的URL,并将其路由到该操作,然后请求的属性过滤器启动。您只是在返回到main方法之前返回了结果,仅此而已。将属性视为该方法的扩展,它们仍然是执行与用户调用的URL关联的操作过程的一部分。@ADyson如果操作方法确实得到执行,那么为什么ProfileActionAttribute.OnActionExecuted()没有被调用?我不确定,抱歉。可能是因为您在同一个过滤器中设置了结果。如果切换属性的执行顺序(使用属性声明中的order参数完成),了解会发生什么是很有趣的。ASP.NETMVC是开源的,您可以随时亲自查看其逻辑。本文也可能是相关的,或者至少提供上下文。