Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Action Filter is not a an attribute class

I have this action filter that I want to call, I have already declared it in Startup.cs. However, when I call it above my class, I get this error:

LogUserNameFilter is not an attribute class

I'm not sure what I'm missing.

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>();

Class declaration

[LogUserNameFilter]
public class HomeController : Controller{


}
like image 993
JianYA Avatar asked Dec 20 '18 11:12

JianYA


1 Answers

In order to use a class as an attribute, the class should inherit the Attribute class, specifically in your case, you should inherit 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);
    }
}

You can find more use information in MSDN

like image 140
Ofiris Avatar answered Jan 02 '23 21:01

Ofiris