【问题标题】:.NET Core Action Filter is not a an attribute class.NET Core 操作筛选器不是属性类
【发布时间】:2018-12-20 11:33:58
【问题描述】:

我有我想调用的这个动作过滤器,我已经在 Startup.cs 中声明了它。但是,当我在班级上方调用它时,出现此错误:

LogUserNameFilter 不是属性类

我不确定我错过了什么。

public class LogUserNameFilter : IActionFilter
{
    private readonly RequestDelegate next;

    public LogUserNameFilter(RequestDelegate next)
    {
        this.next = next;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        throw new NotImplementedException();
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        LogContext.PushProperty("UserName", context.HttpContext.User.Identity.Name);
    }
}

Startup.cs

services.AddScoped<LogUserNameFilter>();

类声明

[LogUserNameFilter]
public class HomeController : Controller{


}

【问题讨论】:

标签: asp.net-core asp.net-core-mvc


【解决方案1】:

为了使用一个类作为属性,该类应该继承Attribute类,特别是在你的情况下,你应该继承ActionFilterAttribute

public class LogUserNameFilter : ActionFilterAttribute, IActionFilter
{
    private readonly RequestDelegate next;

    public LogUserNameFilter(RequestDelegate next)
    {
        this.next = next;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        throw new NotImplementedException();
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        LogContext.PushProperty("UserName", context.HttpContext.User.Identity.Name);
    }
}

您可以在MSDN找到更多使用信息

【讨论】:

  • 您将无法将此类实例化为属性。
  • @poke,为什么需要实例化该类?
  • 如果您执行[MyAttribute],则该属性将被实例化。为了实例化它,它需要一个只有常量值参数的构造函数。您将无法在此处将RequestDelegate 传递给[LogUserNameFilter(…)]
  • @Ofiris poke 是正确的。你认为你将如何使用这个过滤器。你有例子吗
猜你喜欢
  • 2019-07-29
  • 2017-08-06
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 2018-03-29
  • 2016-06-09
  • 2015-10-04
  • 1970-01-01
相关资源
最近更新 更多