加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 使用简单的ActionFilterAttribute运行时出错

发布时间:2020-12-16 07:28:36 所属栏目:asp.Net 来源:网络整理
导读:开始编写一个简单的过滤器,在每个动作加载时从请求中提取一些东西,从其他堆栈流中复制一些代码,如下所示: public class TestKeyAttribute : ActionFilterAttribute{ public override void OnActionExecuting(HttpActionContext context) { if (context.Requ
开始编写一个简单的过滤器,在每个动作加载时从请求中提取一些东西,从其他堆栈流中复制一些代码,如下所示:

public class TestKeyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        if (context.Request.Properties.ContainsKey("test"))
        {
        // do stuff
        }
    }
}

然后添加其余的属性:

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 – 我现在需要注册属性吗?

请注意:我不希望附加到Web API控制器的过滤器(将其添加到GlobalConfiguration.Configuration.Filters确实有效),而是普通的Web控制器.

编辑:我知道我可以通过继承IActionFilter而使用OnActionExecuting来实现这一点,我只是好奇为什么这种方法不起作用,因为一堆教程似乎应该说.

解决方法

使用MVC4时,自定义属性所在的项目必须包含对System.Web.Http.Common库的引用.我使用NuGet将它添加到我的项目中,嘿presto!错误消失了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读