Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not firing?

slashp picture slashp · Oct 20, 2012 · Viewed 50.7k times · Source

I'm trying to implement what's seen here: http://www.piotrwalat.net/nhibernate-session-management-in-asp-net-web-api/ but I'm having an issue with my NhSessionManagementAttribute.

I've set breakpoints on my OnActionExecuting(HttpActionContext actionContext) to see whether the function was ever being called -- it wasn't.

I double-checked my global.asax.cs file & found I am in fact registering the ActionFilter with:

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

I have also decorated both my controller class itself, as well as its actions with the attribute to no avail:

public class ClientsController : ApiController {
    static readonly ClientRepository repository = new ClientRepository();

    [NhSessionManagement]
    public IEnumerable<Client> GetAllClients() {
        return repository.GetAll();
    }

    [NhSessionManagement]
    public Client GetClient(int id) {
        Client client = repository.Get(id);
        if (client == null) {
            throw new HttpResponseException(
                new HttpResponseMessage(HttpStatusCode.NotFound)
            );
        }
        return client;
    }
}

Why would this action filter not be firing any of the events within?

Answer

Troy Dai picture Troy Dai · Oct 21, 2012

If you're working in a project contains both MVC and WebAPI assembilies, could you check what's the namespace your ActionFilterAttribute's namespace. It's fairly confusing cause there are two ActionFilterAttributes under both:

  • WebAPI: System.Web.Http.Filters
  • MVC: System.Web.Http.Mvc