相关疑难解决方法(0)

MVC 4 Web API寄存器过滤器

我正在使用MVC 4 Web API为应用程序创建服务层.我正在尝试创建一个全局过滤器,它将对API的所有传入请求起作用.现在我明白这必须配置不同于标准的MVC全局动作过滤器.但我遇到的问题是我在网上找到的任何一个例子.

我遇到的问题是使用Web API注册过滤器.

我的Global.asax设置如下......

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        MVCConfig.RegisterRoutes(RouteTable.Routes);
        MVCConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        WebApiConfig.RegisterRoutes(GlobalConfiguration.Configuration);
        WebApiConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的标准Mvc路由和过滤器正常工作.和我的WebApi路由一样.这是我的webApi过滤器注册...

public static void RegisterGlobalFilters(System.Web.Http.Filters.HttpFilterCollection filters)
{
    filters.Add(new PerformanceTestFilter());
}
Run Code Online (Sandbox Code Playgroud)

这是PerformanceTestFilter ......

public class PerformanceTestFilter : ActionFilterAttribute
{
    private readonly Stopwatch _stopWatch = new Stopwatch();

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        _stopWatch.Reset();
        _stopWatch.Start();
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        _stopWatch.Stop();
        var executionTime = _stopWatch.ElapsedMilliseconds;
        // Do something with the executionTime
    }
}
Run Code Online (Sandbox Code Playgroud)

当使用标准Mvc GlobalFilterCollection注册时,此过滤器工作正常,但是当我尝试使用System.Web.Http.Filters.HttpFilterCollection注册它时,我收到一条错误消息,指出它不能分配给参数类型System.Web.Http. Filters.IFilter. …

c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api

10
推荐指数
1
解决办法
2万
查看次数