【问题标题】:ASP.Net Core filters with arguments and DI带有参数和 DI 的 ASP.Net Core 过滤器
【发布时间】:2017-08-03 13:41:07
【问题描述】:

有没有办法在 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')] 而不是不带参数的[TestFilter]

【问题讨论】:

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


    【解决方案1】:

    如果您查看源代码,则有。不过从来没有尝试过,所以你必须自己尝试一下(不能在工作中测试它,也不能在家里测试它)。

    文档将其中之一命名为无类型参数:

    [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) { }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2016-05-26
      • 2021-04-05
      • 2020-01-23
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2017-07-28
      • 2015-12-08
      相关资源
      最近更新 更多