ASP.NET Core MVC应用程序设置

问题描述:

我正在尝试在ASP.NET Core MVC项目上使用配置变量.

I'm trying to use configuration variables on my ASP.NET Core MVC project.

这是我到目前为止所到之处:

This is where I've got so far:

  1. 创建了一个appsettings.json
  2. 创建了AppSettings类
  3. 现在我正尝试将其注入ConfigureServices上,但是无法识别我的Configuration类,或者在使用完整引用:"Microsoft.Extensions.Configuration"时无法识别GetSection方法,即

无法识别配置类

无法识别GetSection方法

关于如何使用此功能的任何想法?

Any ideas on how to use this?

.NET Core中的整个配置方法确实非常灵活,但一开始并不十分明显.举个例子可能最容易解释:

The whole configuration approach in .NET Core is really flexible, but not at all obvious at the beginning. It's probably easiest to explain with an example:

假设一个 appsettings.json 文件看起来像这样:

Assuming an appsettings.json file that looks like this:

{
  "option1": "value1_from_json",

  "ConnectionStrings": {
    "DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

要从 appsettings.json 文件中获取数据,您首先需要在Startup.cs中设置ConfigurationBuilder,如下所示:

To get the data from appsettings.json file you first need to set up a ConfigurationBuilder in Startup.cs as follows:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

然后可以直接访问配置,但是创建用于保存该数据的Options类比较整洁,然后可以将其注入到控制器或其他类中.这些选项类中的每一个都代表appsettings.json文件的不同部分.

You can then access the configuration directly, but it's neater to create Options classes to hold that data, which you can then have injected into your controller or other classes. Each of those options classes represent a different section of the appsettings.json file.

在此代码中,将连接字符串加载到ConnectionStringSettings类中,将另一个选项加载到MyOptions类中. .GetSection方法获取 appsettings.json 文件的特定部分.同样,这在Startup.cs中:

In this code the connections strings are loaded into a ConnectionStringSettings class and the other option is loaded into a MyOptions class. The .GetSection method gets a particular part of the appsettings.json file. Again, this is in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    ... other code

    // Register the IConfiguration instance which MyOptions binds against.
    services.AddOptions();

    // Load the data from the 'root' of the json file
    services.Configure<MyOptions>(Configuration);

    // load the data from the 'ConnectionStrings' section of the json file
    var connStringSettings = Configuration.GetSection("ConnectionStrings");
    services.Configure<ConnectionStringSettings>(connStringSettings);

这些是设置数据被加载到的类.请注意属性名称如何与json文件中的设置配对:

These are the classes that the settings data are loaded into. Note how the property names pair up with the settings in the json file:

public class MyOptions
{
    public string Option1 { get; set; }
}

public class ConnectionStringSettings
{
    public string DefaultConnection { get; set; }
}

最后,您可以通过将OptionsAccessor注入到控制器中来访问这些设置,如下所示:

Finally, you can then access those settings by injecting an OptionsAccessor into the controller as follows:

private readonly MyOptions _myOptions;

public HomeController(IOptions<MyOptions > optionsAccessor)
{
    _myOptions = optionsAccessor.Value;
    var valueOfOpt1 = _myOptions.Option1;
}

通常,整个配置设置过程在Core中是完全不同的. Thomas Ardal在他的网站上对此有很好的解释: http://thomasardal. com/appsettings-in-asp-net-core/

Generally, the whole configurations settings process is pretty different in Core. Thomas Ardal has a good explanation of it on his site here: http://thomasardal.com/appsettings-in-asp-net-core/

还有关于 ASP.NET Core中的配置的更详细的说明在Microsoft文档中.

注意:在Core 2中,这一切都有所发展,我需要重新审视上面的一些答案,但与此同时,

NB: This has all evolved a bit in Core 2, I need to revisit some of the answer above, but in the meantime this Coding Blast entry by Ibrahim Šuta is an excellent introduction with plenty of examples.

注意事项2:使用上述方法很容易造成许多配置错误,请查看此答案(如果它不适合您)

NB No. 2: There are a number of configuration mistakes that are easy to make with the above, have a look at this answer if it doesn't behave for you.