4

Started writing a simple filter to pull some stuff from request on each action load, copied some code from other stackoverflows that looks like so:

public class TestKeyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        if (context.Request.Properties.ContainsKey("test"))
        {
        // do stuff
        }
    }
}

Then added the attribute with the rest:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    GlobalConfiguration.Configuration.Filters.Add(new ElmahHandledErrorLoggerFilter());
    filters.Add(new HandleErrorAttribute());
    filters.Add(new TestKeyAttribute());
}

On run, results in this error:

The given filter instance must implement one or more of the following filter
interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.

Most of the links I've found relate to MVC 3, and this seems to work; I am however using MVC 4 and using Web API - is there some other way I need to register the attribute now?

Just a note: I don't want the filter attached to Web API controllers (adding it to GlobalConfiguration.Configuration.Filters does work, though), but rather the normal web controllers.

Edit: I know I can get this working by inheriting from IActionFilter instead and using OnActionExecuting, I'm just curious why this approach doesn't work, since a bunch of tutorials seem to say it should.

intrepidus
  • 974
  • 2
  • 12
  • 24

3 Answers3

7

I had the same error and was puzzled as ElmahHandledErrorLoggerFilter does implement IExceptionFilter.

After investigation, I kicked myself, I'd added the filters.Add(new ElmahHandledErrorLoggerFilter()); to the MVC site config under the FilterConfig class. Adding config.Filters.Add(new ElmahHandleErrorApiAttribute()); instead to the WebApiConfig class works.

Note: I'm using WebAPi v1 here but I've configured a v2 project in the same way.

A. Murray
  • 2,761
  • 5
  • 27
  • 40
3

The reason this doesn't work is that your filter is a WebAPI filter, which is not interchangeable with Mvc filters. The Mvc and WebAPI FilterAttribute and related classes and interfaces have many of the same names (which is why the tutorials appear to say this should work), but they live in different namespaces. Mvc filter classes live in System.Web.Mvc and WebAPI classes live in System.Web.Http.

Further reading here: https://stackoverflow.com/a/23094418/22392

Community
  • 1
  • 1
Patrick
  • 5,970
  • 4
  • 24
  • 21
1

When using MVC4, the project where your custom attribute resides must contain a reference to the System.Web.Http.Common library. I added it to my project using NuGet and hey presto! the error goes away.