简体   繁体   English

OnActionExecuted 在 Web API 中被调用两次

[英]OnActionExecuted being called twice in Web API

I am trying to do some stuff after my controller is done with the action at OnActionExecuted.在我的控制器完成 OnActionExecuted 的操作后,我正在尝试做一些事情。 However the method is called twice.但是该方法被调用两次。

My filter method我的过滤方法

public class TestFilter: ActionFilterAttribute
{
  public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {

       //do stuff here


    }
}

and my controller和我的控制器

[TestFilter]
  public class BaseController : ApiController
{
 public LoginResponseDTO Login(LoginRequestDTO loginRequestDTO)
    {

 //do login stuff
    }

}

when i try this filter, the onActionExecuted Method gets called twice which causes my action in the method to be applied twice to the response.当我尝试这个过滤器时,onActionExecuted 方法被调用两次,这导致我在该方法中的操作被应用于响应两次。 I have searched for a reason but cannot find a solution.我已经寻找了一个原因,但找不到解决方案。

Any Ideas?有什么想法吗?

The answer is from @Martijn comments above:答案来自上面的@Martijn 评论:

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
 public class TestFilter: ActionFilterAttribute

All credits goes to him.所有的功劳都归于他。 (Note: I'll remove the post, if he decide to add the comment as answer) (注意:如果他决定添加评论作为答案,我将删除该帖子)

For me the issue was I was calling /myApi/action which was redirecting to /myApi/action/ and this caused OnActionExecuted() to run twice.对我来说,问题是我正在调用 /myApi/action 重定向到 /myApi/action/ 这导致 OnActionExecuted() 运行两次。

I filtered out where filterContext.Result is RedirectResult within OnActionExecuted since I wasn't interested in running my code then.我过滤掉了onActionExecuted 中 filterContext.Result 是 RedirectResult 的位置,因为那时我对运行我的代码不感兴趣。 The HTTP status code showed as 200 on both the calls so filtering by that won't work. HTTP 状态代码在两个调用中都显示为 200,因此过滤不起作用。

You can override the AllowMultiple inside your ActionFilterAttribute, like so:您可以在 ActionFilterAttribute 中覆盖 AllowMultiple,如下所示:

public override bool AllowMultiple { get { return false; } }

public override void OnActionExecuting(HttpActionContext actionContext)
{
  //Your logic
}

That will stop your ActionFilter being called twice.这将阻止您的 ActionFilter 被调用两次。 Also check that it is not registered twice.还要检查它是否没有注册两次。 Check out this stackoverflow answer to see more about that.查看此stackoverflow 答案以了解更多相关信息。

Do be aware that AttributeUsage attribute is a single-use attribute--it can't be applied more than once to the same class, as you will find in the remarks section of this .请注意 AttributeUsage 属性是一次性属性——它不能多次应用于同一个类,正如您将在.

If you have registered the custom filter in Global.asax.cs, like this:如果您在 Global.asax.cs 中注册了自定义过滤器,如下所示:

GlobalConfiguration.Configuration.Filters.Add(new TestFilterAttribute());

Please revoke the attribute above your custom controller.请撤销自定义控制器上方的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM