[英]ASP.NET Core 2.1 Using variable outside a function
I have this TypeFilter我有这个类型过滤器
[TypeFilter(typeof(ValidateRolesFilter), Arguments = new object[] {
configuration["key"], RoleGlobals.SystemAdministrator
})]
public IActionResult About()
{
return View();
}
In the class constructor above, I have declared configuration like this在上面的类构造函数中,我已经声明了这样的配置
public HomeController(IApplicationUserClient getUserClient, IConfiguration configuration)
{
this.getUserClient = getUserClient;
this.configuration = configuration;
}
However, when I try to declare configuration["Item"], in my typefilter, it won't let me.但是,当我尝试在我的类型过滤器中声明配置 ["Item"] 时,它不会让我这样做。 I can only do it inside functions.
我只能在函数内部做。
What can I do to make it so that I can use my configuration variable outside the function?我该怎么做才能在函数之外使用我的配置变量? I tried making it a constant but it didn't work because it reads from appsettings.json.
我尝试将其设为常量,但它不起作用,因为它从 appsettings.json 读取。
You don't.你没有。
[TypeFilter(typeof(ValidateRolesFilter), Arguments = new object[] {
configuration["key"], RoleGlobals.SystemAdministrator})]
The line above it what is called an Attributes (C#) .它上面的那一行叫做Attributes (C#) 。 Attributes are compile time directives that can read at runtime.
属性是可以在运行时读取的编译时指令。
The variable configuration["key"]
is loaded at run-time.变量
configuration["key"]
在运行时加载。 Therefore the compiler will fail.因此编译器将失败。
Here is another design.这是另一个设计。 Instantiate the
ValidateRolesFilter
in your constructor.在构造函数中实例化
ValidateRolesFilter
。
public HomeController(IApplicationUserClient getUserClient, IConfiguration configuration)
{
this.getUserClient = getUserClient;
this.configuration = configuration;
// This is just a guess; I have no idea what this object is
this.canAccessAbout = new ValidateRolesFilter(configuration["key"], RoleGlobals.SystemAdministrator);
}
Then in your About method:然后在你的 About 方法中:
public IActionResult About()
{
// again, this is just a guess
if (this.canAccessAbout.Validate())
{
return View();
}
else
{
// redirect them or display error page
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.