ASP.Net Core过滤器带有参数和DI

时间:2017-03-13 13:52:42

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

有一种方法可以在ASP.NET Core中使用参数和DI进行过滤吗?

我的工作TestFilterAttributeTestFilterFilter和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)
        {


        }
    }
}

并希望只使用[TestFilter('MyFirstArgument', 'MySecondArgument')]和agruments代替[TestFilter]而不带参数

1 个答案:

答案 0 :(得分:9)

如果你看一下来源,就有。从来没有尝试过,所以你必须自己尝试一下(不能在工作中测试它和家里的互联网问题)。

文档为其中一个命名,用于无类型参数:

[TypeFilter(typeof(AddHeaderAttribute),
    Arguments = new object[] { "Author", "Steve Smith (@ardalis)" })]
public IActionResult Hi(string name)
{
    return Content($"Hi {name}");
}

TypeFilterAttribute的xmldoc说

    /// <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; }

或者,您可以向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) { }
    }
}