错误与简单ActionFilterAttribute运行 [英] Error on run with simple ActionFilterAttribute
问题描述
开始写一个简单的过滤器,从每个动作负载要求拉一些东西,复制从其他stackoverflows一些code,看起来像这样:
Started writing a simple filter to pull some stuff from request on each action load, copied some code from other stackoverflows that looks like so:
public class TestKeyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
if (context.Request.Properties.ContainsKey("test"))
{
// do stuff
}
}
}
然后加入其余的属性:
Then added the attribute with the rest:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandledErrorLoggerFilter());
filters.Add(new HandleErrorAttribute());
filters.Add(new TestKeyAttribute());
}
在运行,导致此错误:
The given filter instance must implement one or more of the following filter
interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.
大多数我发现的链接涉及到MVC 3,这似乎工作;但是我使用MVC 4并使用Web API - ?有一些其他办法,我现在需要注册的属性。
Most of the links I've found relate to MVC 3, and this seems to work; I am however using MVC 4 and using Web API - is there some other way I need to register the attribute now?
刚一说明:我不想连接到网络API控制器过滤器(它添加到GlobalConfiguration.Configuration.Filters没有工作,虽然),而是正常的网络控制器
Just a note: I don't want the filter attached to Web API controllers (adding it to GlobalConfiguration.Configuration.Filters does work, though), but rather the normal web controllers.
编辑:我知道我可以从IActionFilter继承,而不是使用OnActionExecuting,我只是好奇为什么这种方法是行不通的,因为一堆教程,得到这个工作似乎说应该。
I know I can get this working by inheriting from IActionFilter instead and using OnActionExecuting, I'm just curious why this approach doesn't work, since a bunch of tutorials seem to say it should.
推荐答案
在使用MVC4,你的自定义属性所在,必须包含对System.Web.Http.Common库的引用该项目。我使用的NuGet哎preSTO把它添加到我的项目!该错误消失。
When using MVC4, the project where your custom attribute resides must contain a reference to the System.Web.Http.Common library. I added it to my project using NuGet and hey presto! the error goes away.
这篇关于错误与简单ActionFilterAttribute运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!