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

标签 c# asp.net asp.net-core

我无法理解在 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.jsonappsettings.{environment}.json )、命令行、用户 secret (也是 JSON,但存储在您的配置文件中,而不是项目内)和环境进行配置变量。如果您需要其他配置源,可以使用其他现有的提供程序,或者您甚至可以自行推出以使用您喜欢的任何提供程序。

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

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

这对应于类似 { Foo: { Bar: "Baz" } } 的内容例如,在 JSON 中。然后,在 ConfigureServicesStartup.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/

相关文章:

c# - Silverlight 中的 SHA512 不可用,是否有可用的托管库?

asp.net - Powershell 脚本创建一个 "sub"网站

c# - IntelliSense 提示缺少 Microsoft.AspNetCore 包,尽管在那里

c# - 在 resharper intellisense 中显示枚举整数值

c# - 字典性能提升

c# - RegEx表达帮助

javascript - 使用服务器端渲染设置 webpack 以在 asp.net 核心项目中加载 Sass 文件

.net - 未为项目 '.sfproj' 设置 BaseOutputPath/OutputPath 属性

c# - 如何在 EasyNetQ 中获取现有的 Exchange 或队列?

asp.net - 如何使用网站中的 'Launch'按钮启动游戏?