[英]ASP.NET Web API ActionFilter example
我对整个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上的操作已按预期调用并成功运行。 客户端能够查询服务器以获取必要的信息,并且一切正常,除了没有调用任何动作过滤器方法。
我的理解是,其余的都是“自动地”发生的。 显然这还不够-关于什么是错误的任何暗示? 我需要在某个地方注册这些吗?
你必须确保你的代码使用ActionFilterAttribute
从System.Web.Http.Filters
命名空间 ,而不是一个从System.Web.Mvc
。
所以请检查你有
using System.Web.Http.Filters;
正如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方法,则在“消息”列表中将看到“ OnActionExecuted”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.