我无法理解在Startup.cs中设置动态变量的最佳方法。我希望能够在Controller或View中获取该值。我希望能够将值存储在内存中,而不是JSON文件中。我已经研究过将值设置为会话变量,但这似乎不是一个好的实践或工作。在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
),命令行,用户机密(也是JSON,但存储在您的配置文件中,而不是项目中)和环境变量进行配置。如果您需要其他配置来源,可以使用其他现有提供商,或者您甚至可以自己动手使用任何您喜欢的提供商。
无论您使用哪种配置源,最终结果都将是来自IConfigurationRoot
的所有源的所有配置设置。虽然您可以在技术上直接使用它,但最好使用IOptions<T>
提供的强类型配置和类似配置。简单地说,您创建了一个代表配置中某个部分的类:
public class FooConfig
{
public string Bar { get; set; }
}
例如,对应于JSON中的{ Foo: { Bar: "Baz" } }
之类的东西。然后,在ConfigureServices
的Startup.cs
:
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这样的东西在大多数情况下是没有意义的。但是,如果你真的想要完全记忆,那就有一个memory configuration provider。但是,如果可以,最好外部化您的配置。
好吧,在编译代码之前,双击属性中的settings.settings。你可以给变量一个名称,一个类型,一个范围(用户意味着它可以根据安装进行更改,应用程序意味着它将保持原始值并且不能更改),最后是值。