J. *_*Doe 3 dependency-injection asp.net-core-mvc .net-core asp.net-core
有一种方法可以在ASP.NET Core中使用参数和DI进行过滤吗?
我的工作TestFilterAttribute与TestFilterFilter和DI不带参数:
public class TestFilterAttribute : TypeFilterAttribute
{
public TestFilterAttribute() : base(typeof(TestFilterFilter))
{
}
private class TestFilterFilter : IActionFilter
{
private readonly MainDbContext _mainDbContext;
public TestFilterFilter(MainDbContext mainDbContext)
{
_mainDbContext = mainDbContext;
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
并希望简单地使用[TestFilter('MyFirstArgument', 'MySecondArgument')]agruments而不[TestFilter]需要参数
Tse*_*eng 11
如果你看一下来源就有了.从来没有尝试过,所以你必须自己尝试(无法在工作中测试它和家里的互联网问题).
对于无类型参数,文档为其中一个命名:
[TypeFilter(typeof(AddHeaderAttribute),
Arguments = new object[] { "Author", "Steve Smith (@ardalis)" })]
public IActionResult Hi(string name)
{
return Content($"Hi {name}");
}
Run Code Online (Sandbox Code Playgroud)
xmldoc TypeFilterAttribute说的
/// <summary>
/// Gets or sets the non-service arguments to pass to the <see cref="ImplementationType"/> constructor.
/// </summary>
/// <remarks>
/// Service arguments are found in the dependency injection container i.e. this filter supports constructor
/// injection in addition to passing the given <see cref="Arguments"/>.
/// </remarks>
public object[] Arguments { get; set; }
Run Code Online (Sandbox Code Playgroud)
或者,您可以向您添加属性TestFilterAttribute并在构造函数中分配它们,但这仅在参数是必需的并因此通过构造函数设置时才有效
public class TestFilterAttribute : TypeFilterAttribute
{
public TestFilterAttribute(string firstArg, string secondArg) : base(typeof(TestFilterFilter))
{
this.Arguments = new object[] { firstArg, secondArg }
}
private class TestFilterFilter : IActionFilter
{
private readonly MainDbContext _mainDbContext;
private readonly string _firstArg;
private readonly string _secondArg;
public TestFilterFilter(string firstArg, string secondArg, MainDbContext mainDbContext)
{
_mainDbContext = mainDbContext;
_firstArg= firstArg;
_secondArg= secondArg;
}
public void OnActionExecuting(ActionExecutingContext context) { }
public void OnActionExecuted(ActionExecutedContext context) { }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2606 次 |
| 最近记录: |