Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ASP.NET MVC ActionFilterAttribute - hooks never get called

Hi I`m trying to do something that seems kinda easy, and is documented that way but for some reason its not going that easy.

Basiclly I wrote something like this:

public class CacheControllAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    { 
        //do something
        base.OnResultExecuting(filterContext);
    }
}

However when i try and use this on an action result like this:

[CacheControllAttribute]
public ActionResult SomeAction()
{
    //whatever
}

My custom overriden function never gets called...

any ideas on this? or how to implement this differently?

like image 951
aromasca Avatar asked Jun 28 '11 17:06

aromasca


5 Answers

A probably silly suggestion but did you add it to your global.asax?
This is an example from one of my apps:

public class MvcApplication : System.Web.HttpApplication     
{
  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  {
    filters.Add(new LogonAuthorize());
    filters.Add(new HandleErrorAttribute());
  }
}
like image 81
David McLean Avatar answered Nov 15 '22 07:11

David McLean


My error was that I referenced System.Web.Http.Filters, not System.Web.Mvc

like image 31
Yara Avatar answered Nov 15 '22 08:11

Yara


Finally figured out, it was in the end the fact that I have been putting the filter on a function that has in fact been an ActionResult function, but it was returned by another method that called it, so the filters are only being executed once on the entry point Action.

like image 5
aromasca Avatar answered Nov 15 '22 08:11

aromasca


Have you tried overriding the OnActionExecuting like:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
     base.OnActionExecuting(filterContext);
}

This is the way I write action filters and haven't had a problem with them being called.

like image 1
amurra Avatar answered Nov 15 '22 07:11

amurra


Your code generally looks good to me. It could be related to what you are doing (or not doing) in your Action method. If you aren't returning a view, etc., it's possible your "ResultExecuting" event handler isn't being called. I would grab the sample here and see what gets logged for your action.

like image 1
theoretical Avatar answered Nov 15 '22 09:11

theoretical