63

I'm new to the whole MVC thing and am looking at re-implementing some WCF services using ASP.NET Web API. As part of that, I'd like to implement an action filter that logs all actions and exceptions as well as does timing so I thought I'd start with an Action Filter, however the filter is not being invoked.

public class MyTrackingActionFilter : ActionFilterAttribute, IExceptionFilter 
{
    private Stopwatch stopwatch = new Stopwatch();

    public void OnException(ExceptionContext filterContext)
    {
           ...
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
           ...
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        this.stopwatch.Start();
        Trace.TraceInformation(" Entering {0}", filterContext.RouteData);
    }
}

and on the controller, I have

[MyTrackingActionFilter]
public class MyResourceController : ApiController
{
  ...
}

The routes are setup in Global.asax using calls like:

var routeTemplate = ...
var defaults = new { controller = controllerName, action = methodName };
var constraints = new { httpMethod = new HttpMethodConstraint(myHTTPMethods.Split(',')) };

routes.MapHttpRoute(methodName, routeTemplate, defaults, constraints);

The issue is that the actions on the MyResourceController are invoked as expected and run successfully. The client is able to query the server for the necessary info and all behaves fine, except that none of the action filter methods are ever invoked.

My understanding was that the rest happened "automagically". That's clearly not enough - Any sugestions as to what is wrong? Do I need to register these somewhere?

4

2 回答 2

189

您必须确保您的代码使用ActionFilterAttribute来自System.Web.Http.Filters命名空间而不是来自System.Web.Mvc.

所以请检查你是否有

 using System.Web.Http.Filters;
于 2012-04-24T23:40:36.727 回答
2

正如 Sander 提到的,我尝试了下面的代码,它的动作过滤器正在执行。

public class WebAPIActionFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        PersonController.Messages.Add("OnActionExecuted");
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        PersonController.Messages.Add("OnActionExecuting");
    }
}

public class WebAPIExceptionFilter : System.Web.Http.Filters.ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        PersonController.Messages.Add("OnException");
        actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Something went wrong") };
    }
}

PersonController.Messages 是一个静态字符串列表。如果您想检查 OnActionExecuted 是否正在执行,您可以再次调用相同的 API 方法,您会在 Messages 列表中看到“OnActionExecuted”。

于 2016-08-20T14:58:25.147 回答