gpt4 book ai didi

asp.net-core - .NET Core Action Filter 不是属性类

转载 作者:行者123 更新时间:2023-12-04 11:31:21 25 4
gpt4 key购买 nike

我有这个想要调用的 Action 过滤器,我已经在 Startup.cs 中声明了它。但是,当我在类(class)上方调用它时,出现此错误:

LogUserNameFilter is not an attribute class



我不确定我错过了什么。
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);
}
}

启动文件
services.AddScoped<LogUserNameFilter>();

类声明
[LogUserNameFilter]
public class HomeController : Controller{


}

最佳答案

为了使用类作为属性,该类应该继承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 中找到更多使用信息

关于asp.net-core - .NET Core Action Filter 不是属性类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com