在 Startup .cs ASP.NET CORE 中设置动态变量



我无法理解在启动.cs中设置动态变量的最佳方法。我希望能够在控制器或视图中获取该值。我希望能够将值存储在内存中,而不是 JSON 文件中。我已经研究了将值设置到会话变量中,但这似乎不是好的做法或工作。在启动.cs中设置动态变量的最佳实践是什么?

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//services.AddDbContext<>(options => options.UseSqlServer(Configuration.GetConnectionString("Collections_StatsEntities")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}

全局变量和静态变量不好。 ASP.NET Core 包含专门用于避免这些的内置 DI,因此不要去重新引入它们。正确的方法是使用配置。开箱即用的 ASP.NET Core 应用支持通过 JSON(appsettings.jsonappsettings.{environment}.json(、命令行、用户机密(也是 JSON,但存储在配置文件中,而不是项目内(和环境变量进行配置。如果您需要其他配置源,还有其他现有的提供程序可用,或者您甚至可以自行使用任何您喜欢的提供程序。

无论您使用哪种配置源,最终结果将是所有源的所有配置设置都进入IConfigurationRoot。虽然从技术上讲,您可以直接使用它,但最好使用IOptions<T>和类似提供的强类型配置。简单地说,你创建一个类来表示配置中的某个部分:

public class FooConfig
{
public string Bar { get; set; }
}

例如,这将对应于 JSON 中的{ Foo: { Bar: "Baz" } }之类的内容。然后,在Startup.csConfigureServices

services.Configure<FooConfig>(Configuration.GetSection("Foo"));

最后,在控制器中,例如:

public class FooController : Controller
{
private IOptions<FooConfig> _config;
public FooController(IOptions<FooConfig> config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
}
...
}

配置在启动时读取,从技术上讲,之后存在于内存中,因此您对必须使用 JSON 之类的东西的抱怨在大多数情况下毫无意义。但是,如果您确实想要完全在内存中,则有一个内存配置提供程序。但是,如果可以的话,最好将配置外部化。

好吧,在编译代码之前,双击属性中的设置。设置。 您可以为变量指定名称、类型、作用域(用户意味着它可以在每次安装时更改,应用程序意味着它将保持原始值不变且无法更改(,最后是值。

最新更新