2
votes

I am facing issue in using WebAPI action filter.

I wrote the following custom filter to perform some logic on the http request header before executing the controller method.

using System;
using System.Web.Mvc;


    namespace WebApi.Filters
    {
        public class dataCheck : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                Console.Write("custom filter called");
            }
        }
    }

Then added filter attribute on top of controller method

[dataCheck ]
[HttpGet]
[Route("GetInfo")]
public LatestInfo GetInfo()
{

    TestContext context = new TestContext ();
    LatestInfo latestReleaseInfo = new LatestInfo ();
    return LatestInfo ;

}

Problem: I put debugger to my custom filter and found it is never invoked.

What is wrong here?

Am i using the right type filter for my logic?

Please advise.

2

2 Answers

1
votes

You have to be sure your code uses the ActionFilterAttribute from the System.Web.Http.Filters namespace and not the one from System.Web.Mvc.

0
votes

Karthik's answer is correct - there are a couple of other things in your class that you should correct.

Your override function should accept a HttpActionContext as opposed to ActionExecutingContext. Also, you should call base.OnActionExecuting(actionContext); at the end of your function

using System;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebApi.Filters
{
    public class dataCheck : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            Console.WriteLine("debugger stop here");

            // custom filter code

            base.OnActionExecuting(actionContext);
        }
    }
}