简体   繁体   English

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

[英]Set Dynamic Variables in Startup.cs in ASP.NET CORE

I'm having trouble understanding the best way to SET dynamic variables in the Startup.cs. 我在理解Startup.cs中设置动态变量的最佳方法时遇到了麻烦。 I want to be able to GET that value in a Controller OR in a View. 我希望能够在Controller或View中获取该值。 I want to be able to store the values in memory, not a JSON file. 我希望能够将值存储在内存中,而不是JSON文件中。 I've looked into setting values into a session variables, but that does not seem to be good practice or work. 我已经研究过将值设置为会话变量,但这似乎不是一种好的做法或工作。 What is best practice to set dynamic variables in the Startup.cs? 在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?}");
        });
    }
}

Globals and statics are bad. 全局变量和静态变量是有害的。 ASP.NET Core includes DI built-in specifically to avoid these, so don't go and reintroduce them. ASP.NET Core包含专门为避免这些问题而内置的DI,因此请不要重新引入它们。 The correct approach is to use configuration. 正确的方法是使用配置。 Out of the box, an ASP.NET Core app supports configuration via JSON ( appsettings.json and appsettings.{environment}.json ), command-line, user secrets (also JSON, but stored in your profile, rather than in-project), and environment variables. 一个现成的ASP.NET Core应用程序支持通过JSON( appsettings.jsonappsettings.{environment}.json ),命令行,用户机密(也是JSON,但存储在您的配置文件中而非项目中)进行配置)和环境变量。 If you need other sources of configuration, there's other existing providers available, or you can even roll your own to use whatever you like. 如果您需要其他配置源,则可以使用其他现有提供程序,或者甚至可以自己滚动使用任何所需的提供程序。

Whichever config source you use, the end result will be all the configuration settings from all sources going into IConfigurationRoot . 无论使用哪种配置源,最终结果都是来自所有源的所有配置设置都进入IConfigurationRoot While you can technically use that directly, it's better to use the strongly-typed configuration provided by IOptions<T> and similar. 尽管您可以从技术上直接使用它,但最好使用IOptions<T>和类似选项提供的强类型配置。 Simply, you create a class that represents some section in your config: 只需创建一个代表配置中某些部分的类:

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

Which would correspond to something like { Foo: { Bar: "Baz" } } in JSON, for example. 例如,与JSON中的{ Foo: { Bar: "Baz" } }类似。 Then, in ConfigureServices in Startup.cs : 然后,在Startup.cs ConfigureServices中:

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

Finally, in your controller, for example: 最后,在您的控制器中,例如:

 public class FooController : Controller
 {
     private IOptions<FooConfig> _config;

     public FooController(IOptions<FooConfig> config)
     {
         _config = config ?? throw new ArgumentNullException(nameof(config));
     }

     ...
 }

Configuration is read at startup, and technically exists in memory afterwards, so your complaint about having to use something like JSON is meaningless for the most part. 配置是在启动时读取的,从技术上讲,配置是在内存中存在的,因此您对于必须使用JSON之类的抱怨在大多数情况下是没有意义的。 However, if you truly want completely in-memory, there is a memory configuration provider . 但是,如果您真正想要完全在内存中,则可以使用内存配置提供程序 However, it's always better to externalize your config if you can. 但是,如果可以的话,最好外部化您的配置。

Well, double click your settings.settings in your properties before you compile your code. 好吧,在编译代码之前,双击属性中的settings.settings。 you can give the variable a name, a type, a scope (user is means that it can be changed per installation, application means it will stay the way it is with the original value and cannot be changed), and lastly the value. 您可以为变量指定名称,类型,范围(“ user是”表示可以在每次安装时更改它,“ application”表示将保持其原始值不变且无法更改),最后是该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM