ASP.NET Web API ActionFilter 示例 [英] ASP.NET Web API ActionFilter example
问题描述
我是整个 MVC 的新手,正在考虑使用 ASP.NET Web API 重新实现一些 WCF 服务.作为其中的一部分,我想实现一个记录所有动作和异常以及计时的动作过滤器,所以我想我会从动作过滤器开始,但是没有调用过滤器.
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);
}
}
在控制器上,我有
[MyTrackingActionFilter]
public class MyResourceController : ApiController
{
...
}
使用如下调用在 Global.asax 中设置路由:
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);
问题是 MyResourceController 上的操作按预期调用并成功运行.客户端能够向服务器查询必要的信息并且一切正常,只是没有调用任何操作过滤器方法.
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?
推荐答案
您必须确保您的代码使用 ActionFilterAttribute
来自 System.Web.Http.Filters
命名空间 而不是来自 System.Web.Mvc
的那个.
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
.
所以请检查您是否有
using System.Web.Http.Filters;
这篇关于ASP.NET Web API ActionFilter 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!