我无法理解在 Startup.cs 中设置动态变量的最佳方法。我希望能够在 Controller 或 View 中获取该值。我希望能够将值存储在内存中,而不是 JSON 文件中。我已经研究过将值设置为 session 变量,但这似乎不是一个好的实践或工作。在 Startup.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.json
和 appsettings.{environment}.json
)、命令行、用户 secret (也是 JSON,但存储在您的配置文件中,而不是项目内)和环境进行配置变量。如果您需要其他配置源,可以使用其他现有的提供程序,或者您甚至可以自行推出以使用您喜欢的任何提供程序。
无论您使用哪个配置源,最终结果都将是所有源的所有配置设置进入 IConfigurationRoot
。虽然从技术上讲您可以直接使用它,但最好使用 IOptions<T>
提供的强类型配置。和类似的。简而言之,您创建一个代表配置中某些部分的类:
public class FooConfig
{
public string Bar { get; set; }
}
这对应于类似 { Foo: { Bar: "Baz" } }
的内容例如,在 JSON 中。然后,在 ConfigureServices
在Startup.cs
:
services.Configure<FooConfig>(Configuration.GetSection("Foo"));
最后,在您的 Controller 中,例如:
public class FooController : Controller
{
private IOptions<FooConfig> _config;
public FooController(IOptions<FooConfig> config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
}
...
}
配置是在启动时读取的,并且从技术上讲,配置随后存在于内存中,因此您对必须使用 JSON 之类的东西的提示在大多数情况下是没有意义的。然而,如果你真的想要完全在内存中,有一个 memory configuration provider 。但是,如果可以的话,最好将您的配置外部化。
关于c# - 在 ASP.NET CORE 中的 Startup.cs 中设置动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52320432/