ServiceStack.RequestFilterAsyncAttribute错误:System.ArgumentNullException:值不能为null。参数名称:方​​法

时间:2019-09-27 16:18:09

标签: c# servicestack

我遇到了运行时错误,并且也找到了解决方法(最后)。只是好奇为什么不能将公共属性用于构造函数。 RequestFilterAsyncAttributeRequestFilterAttribute没关系,顺便说一句。

例外情况

public class CustomTokenFilterAttribute : RequestFilterAsyncAttribute
{
    public CustomTokenFilterAttribute() {}
    public CustomTokenFilterAttribute(params string[] roles)
    {
        RequireRoles = roles?.ToList();
    }

    public override async Task ExecuteAsync(IRequest req, IResponse res, object requestDto) {}

    public List<string> RequireRoles { get; private set; } // public property: ERROR here
}
System.ArgumentNullException: Value cannot be null.  Parameter name: method
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression arg0)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
at Funq.Container.GenerateAutoWireFnForProperty(Container container, MethodInfo propertyResolveFn, PropertyInfo property, Type instanceType) in C:\\BuildAgent\\work\\3481147c480f4a2f\\src\\ServiceStack\\Funq\\Container.Adapter.cs:line

但是,这种方法可以解决问题。

public class CustomTokenFilterAttribute : RequestFilterAsyncAttribute
{
    public CustomTokenFilterAttribute() {}
    public CustomTokenFilterAttribute(params string[] roles)
    {
        RequireRoles = roles?.ToList();
    }

    public override async Task ExecuteAsync(IRequest req, IResponse res, object requestDto) {}

    readonly List<string> RequireRoles; // private property: ok
}

1 个答案:

答案 0 :(得分:0)

因为国际奥委会正在尝试使用setter将依赖项注入到公共属性中。

您可以将其更改为不带setter的只读公共属性,例如:

public class CustomTokenFilterAttribute : RequestFilterAsyncAttribute
{
    public List<string> RequireRoles { get; } 
    public CustomTokenFilterAttribute(params string[] roles)
    {
        RequireRoles = roles?.ToList();
    }
}