C# - 配置变量中的自定义ActionFilter Pass
我有一个自定义的操作过滤器,该过滤器带有属性,但我需要该属性来自我的appsettings.json文件。我将配置传递到控制器中,但是当我尝试传递“ _config.getValue< string>(“ mystring”)“)” “ the“ _config”是红色的,并带有消息
:非静态字段,方法或属性所需的参考是“ mycontroller._config'
操作过滤器
public class MyActionFilter : ActionFilterAttribute
{
public string Property1 { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
...
}
}
控制器
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
private readonly IConfiguration _config;
public MyController(IConfiguration config) {
_config = config;
}
[Authorize]
[HttpPost(Constants.ActionName.MyMethod, Name = nameof(MyMethod))]
[MyActionFilter(Property1 = _config.GetValue<string>("myString"))] // Breaks here!
public ActionResult<string> MyMethod()
{
...
}
}
我该如何执行此操作?或者至少,如何避免为我的操作过滤器属性进行硬编码?
I have a custom action filter that takes in a property but I need the property to come from my appsettings.json file. I pass my configuration into the controller, but when I try to pass in the "_config.GetValue< string >("myString")" the "_config" is red underlined with the message:
An object reference is required for the non-static field, method, or property 'MyController._config'
Action Filter
public class MyActionFilter : ActionFilterAttribute
{
public string Property1 { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
...
}
}
Controller
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
private readonly IConfiguration _config;
public MyController(IConfiguration config) {
_config = config;
}
[Authorize]
[HttpPost(Constants.ActionName.MyMethod, Name = nameof(MyMethod))]
[MyActionFilter(Property1 = _config.GetValue<string>("myString"))] // Breaks here!
public ActionResult<string> MyMethod()
{
...
}
}
How can I do this? Or at least, how can I avoid hardcoding a value for my action filter properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您当前的方法不起作用,因为在编译时评估了构造函数参数和属性的属性。
您可以像这样的过滤器中使用服务定位器模式:
但是,此方法是有争议的,因为服务定位器模式被认为是反图案。
另一种方法是使用
ServiceFilter
。首先,为操作过滤器创建一个构造函数:其次,将操作过滤器更改为控制器中的服务滤波器:
第三,注册操作过滤器:
这是一个关于该主题的很棒的博客文章:
Your current approach does not work because constructor parameters and properties of attributes are evaluated at compile time.
You could use the service locator pattern in your filter like so:
However, this approach is debatable because the service locator pattern is considered an anti-pattern.
Another approach is to use a
ServiceFilter
. First, create a constructor for the action filter:Second, change the action filter to a service filter in the controller:
Third, register the action filter:
Here is a great blogpost about the topic: Dependency Injection in action filters in ASP.NET Core.