本文介绍了ASP.NET的Web API ActionFilter例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的整个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.

我的理解是,剩下的事自动地。这显然​​是不够的 - 任何sugestions,什么是错的?我是否需要注册这些地方?

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?

推荐答案

您必须确定您的code从 System.Web.Http.Filters 命名空间使用ActionFilterAttribute而不是一个来自 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例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:53