ActionScript ASP.NET Web API Example

I'm new to all MVC work, and I am looking at reimplementing some WCF services using the ASP.NET Web API. As part of this, I would like to implement an action filter that logs all actions and exceptions, and also makes a timing, so I thought I would start with an action filter, but the filter is not called.

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 { ... } 

Routes are set in Global.asax using calls such as:

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

The problem is that the actions in MyResourceController invoke, as expected, and succeed. A client can request a server to obtain the necessary information, and everything behaves well, except that none of the action filter methods are called.

I realized that everything else happened "automatically." Honestly, this is not enough - Any judgments about what is wrong? Do I need to register this?

+48
asp.net-web-api
Apr 24 '12 at 23:19
source share
2 answers

You must be sure that your code uses ActionFilterAttribute from the System.Web.Http.Filters namespace , and not from System.Web.Mvc .

So please check that you have

  using System.Web.Http.Filters; 
+169
Apr 24 '12 at 23:40
source share

As Sander said, I tried the code below, its action filter starts.

 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 is a static list of strings. if you want to check if OnActionExecuted is running or not, you can call the same API method again, you will see "OnActionExecuted" in the "Messages" list.

0
Aug 20 '16 at
source share



All Articles