在startup
上,我设置了动作过滤器。
services.AddScoped<CheckThisAttribute>();
动作过滤器本身是
public class CheckThisAttribute : ActionFilterAttribute
{
private readonly Context Db;
private readonly string Name;
public CheckThisAttribute(Context context, string name = "")
{
Db = context;
Name = name;
}
}
并通过
在控制器上消耗[ServiceFilter(typeof(CheckThisAttribute))]
public class MyController : Controller
{
}
您可能已经注意到,我在构造函数中将name
参数设置为可选。
如果我不这样做,我会得到运行时错误。 (上下文是通过DI传递的,但名称不是)
我可以扩展此动作过滤器,以便也可以通过控制器传递name
吗?
[ServiceFilter(typeof(CheckThisAttribute(name="Something")))]
答案 0 :(得分:1)
使用ServiceFilterAttribute
无法获得该结果。
请尝试使用TypeFilterAttribute
,它看起来像这样:
[TypeFilter(typeof(CheckThisAttribute),
Arguments = new object[] { "Method 'Hi' called" })]
这是文档的链接: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.1