【问题标题】:Error resolving ActionFilterAttribute as TypeFilter in .net Core 3.1在 .net Core 3.1 中将 ActionFilterAttribute 解析为 TypeFilter 时出错
【发布时间】:2020-07-23 21:51:48
【问题描述】:

将我的应用程序从 .Net Core 2.2 更新到 3.1 尝试解决 ActionFilter 的依赖项时出现错误。

我有这个过滤器

public class DoSomethingAttribute : ActionFilterAttribute
    {
        private readonly IWorkContext workContext;

        public OneEnum OneParameter { get; set; }

        public AuthorizeAdminAttribute(OneEnum oneParameter, IWorkContext workContext)
        {
            OneParameter = oneParameter;
            workContext = workContext;
        }

         /**more stuff**/
    }

我注册了

services.AddScoped<DoSomethingAttribute>();

我叫它

    [HttpDelete]
    [Authorize]
    [Route("{id:int}")]
    [TypeFilter(typeof(DoSomethingAttribute), Arguments = new object[] { OneEnum.OneValue } )]
    public async Task<IActionResult> Delete(int id)
    {}

使用 .Net core 2.2 版本可以正常工作,但使用 3.1 时出现此错误:

InvalidOperationException: Error while validating the service descriptor 'ServiceType: DoSomethingAttribute Lifetime: Scoped ImplementationType: DoSomethingAttribute': Unable to resolve service for type 'POneEnum' while attempting to activate 'DoSomethingAttribute'.

InvalidOperationException: Unable to resolve service for type 'OneEnum' while attempting to activate 'DoSomethingAttribute'.

有什么想法吗?

【问题讨论】:

  • 只需删除 services.AddScoped() 这一行,你会看到你的错误消失了,IWorkContext 将由 asp.net core 自动注入。
  • 谢谢@Changemyminds,这就是解决方案

标签: c# .net asp.net-core .net-core


【解决方案1】:

这是一个如下所示的工作演示:

public class MyFilterAttribute : TypeFilterAttribute
{
    public MyFilterAttribute(params object[] arguments) : base(typeof(DoSomethingAttribute))
    {
        Arguments = new object[] { arguments };
    }

    public class DoSomethingAttribute : ActionFilterAttribute
    {

        private readonly IWorkContext WorkContext;
        private readonly OneEnum OneParameter;
 
        public DoSomethingAttribute(object[] arguments, IWorkContext workContext)
        {
            OneParameter = (OneEnum)arguments[0];
            WorkContext = workContext;

        }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //do your stuff....
             await base.OnActionExecutionAsync(context, next);
        }
    }
}

将属性添加到控制器:

[MyFilter(OneEnum.OneValue)]
public async Task<IActionResult> Delete(int id)
{}

无需注册如下属性:

services.AddScoped<DoSomethingAttribute>();

【讨论】:

  • 谢谢。我删除了注册,它起作用了。
  • 如果我的解决方案对您有帮助,您能接受吗?
猜你喜欢
  • 2020-05-10
  • 2020-06-19
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 2021-02-05
  • 2018-04-16
  • 2020-09-23
  • 2020-08-22
相关资源
最近更新 更多