ASP.Net Core 2中的全局变量

时间:2018-10-04 20:00:30

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

我正在ASP.NET Core中开发一个Web应用程序,当前有大量密钥,例如条带帐户密钥。与其将它们分散在整个项目中的不同类中,不如将它们全部放置在json中,以便可以在全局范围内对其进行访问。我尝试将它们放在appsettings.json中,但无法在任何地方访问它们。

2 个答案:

答案 0 :(得分:3)

我经常用连接字符串和其他全局常量来做这种事情。首先为所需的变量创建一个类。在我的项目中,它是MDUOptions,但您需要什么。

public class MDUOptions
{
    public string mduConnectionString { get; set; }
    public string secondaryConnectionString { get; set; }
}

现在在您的Startup.cs ConfigureServices方法中:

Action<MDU.MDUOptions> mduOptions = (opt =>
{
    opt.mduConnectionString = Configuration["ConnectionStrings:mduConnection"];
});
services.Configure(mduOptions);
services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<MDUOptions>>().Value);

现在,您可以使用DI通过代码访问它:

public class PropertySalesRepository : IPropertySalesRepository
{
    private static string _mduDb;

    public PropertySalesRepository(MDUOptions options)
    {
        _mduDb = options.mduConnectionString;
    }
    ....
}

在我的情况下,我想要的唯一属性是字符串,但是我可以使用整个选项类。

答案 1 :(得分:2)

在appsettings.json中保留变量。

{
    "foo": "value1",
    "bar": "value2",
}

创建 AppSettings 类。

public class AppSettings
{
    public string foo { get; set; }

    public string bar { get; set; }
}

Startup.cs 文件寄存器中。

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration);
}

用法

public class MyController : Controller
{
    private readonly IOptions<AppSettings> _appSettings;

    public MyController(IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings;
    }
    var fooValue = _appSettings.Value.foo;
    var barValue = _appSettings.Value.bar;
}
相关问题