ASP.NET Web API ActionFilter示例

时间:2012-04-24 23:19:56

标签: c# asp.net-web-api

我是整个MVC的新手,我正在考虑使用ASP.NET Web API重新实现一些WCF服务。作为其中的一部分,我想实现一个动作过滤器,记录所有动作和异常以及定时,所以我认为我会从动作过滤器开始,但是没有调用过滤器。

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);
    }
}

在控制器上,我有

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

使用以下调用在Global.asax中设置路由:

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

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

问题是MyResourceController上的操作按预期调用并成功运行。客户端能够向服务器查询必要的信息,并且所有行为都很好,除了没有调用任何动作过滤器方法。

我的理解是其余的都是“自动地”发生的。这显然是不够的 - 任何关于什么是错的消息?我需要在某处注册吗?

2 个答案:

答案 0 :(得分:180)

您必须确保您的代码使用的是ActionFilterAttribute from the System.Web.Http.Filters namespace,而不是System.Web.Mvc中的代码。

所以请检查你有

 using System.Web.Http.Filters;

答案 1 :(得分:0)

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

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方法,你会看到" OnActionExecuted"在消息列表中。