我创建了一个链接到 ActionFilter
的 TypeFilter
。
TypeFilter
的目的是在 Controller
的 Action
中使用。
TypeFilter
有一些必需的属性(在构造函数中询问)和一些可选参数。
但由于有一些可选属性,并且将来可能会更多,因此创建构造函数来支持每种组合并不是一个机会。为了解决这个问题,我在 TypeFilter 中创建了公共(public)属性,以便能够在属性中设置它们,如下一个示例:
[HttpGet]
[TypeTestFilter(typeof(WeatherForecast), "myparam1", "myparam2", "myparam2", MaxValue = 10, MinValue = 1)]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
TypeFilter
示例代码如下:
public class TypeTestFilter : TypeFilterAttribute
{
public int MaxValue { get; set; }
public int MinValue { get; set; }
public TypeTestFilter(Type type, params string[] parameterNames) : base(typeof(TypeTestActionFilter))
{
this.Arguments = new object[]
{
type,
parameterNames,
MaxValue,
MinValue
};
}
private class TypeTestActionFilter : IActionFilter
{
private readonly Type _type;
private readonly string[] _parameterNames;
private readonly int _maxValue;
private readonly int _minValue;
public TypeTestActionFilter(Type type, string[] parameterNames, int maxValue, int minValue)
{
_type = type;
_parameterNames = parameterNames;
this._maxValue = maxValue;
this._minValue = minValue;
}
public void OnActionExecuting(ActionExecutingContext context)
{
// code.
}
public void OnActionExecuted(ActionExecutedContext context)
{
// code.
}
}
}
如您所见,type
和 parametersNames
是构造函数的参数。当执行 TypeTestActionFilter
时,两个参数都会正确设置值。但 MaxValue
和 MinValue
属性值均未设置。它们只有整数的默认值 (0)。
我在这里缺少什么?为什么这些属性没有使用 Controller
的 Action
中的 TypeFilterAttributes
提供的值进行设置?
如果需要,我可以上传示例项目。
最佳答案
据我所知,属性规范例如:
[TypeTestFilter(typeof(WeatherForecast), "myparam1", "myparam2", "myparam2", MaxValue = 10, MinValue = 1)]
等于:
TypeTestFilter anonymousObject = new TypeTestFilter(typeof(WeatherForecast), "myparam1", "myparam2", "myparam2");
anonymousObject.MaxValue = 10;
anonymousObject.MaxValue = 1;
这意味着我们无法在 TypeTestFilter 的构造方法中获取最大值和最小值,因为它们没有设置。
要解决这个问题,您应该将最大值和最小值传递到构造方法中,如下所示:
public TypeTestFilter(Type type , int minvalue, int maxvalue, params string[] parameterNames) : base(typeof(TypeTestActionFilter))
{
this.Arguments = new object[]
{
type,
parameterNames,
maxvalue,
minvalue
};
}
结果:
关于c# - ASP NET Core TypeFilter 属性未使用过滤器属性提供的值进行设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63184944/