ASP.NET核心MVC应用程序设置

Mi6*_*u3l 6 asp.net-core-mvc asp.net-core

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

这是我到目前为止的地方:

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

配置类无法识别

GetSection方法无法识别

关于如何使用这个的任何想法?

tom*_*dox 8

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

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

{
  "option1": "value1_from_json",

  "ConnectionStrings": {
    "DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)

然后,您可以直接访问配置,但创建选项类来保存该数据更为全面,然后您可以将这些数据注入控制器或其他类.每个选项类都代表appsettings.json文件的不同部分.

在此代码中,连接字符串被加载到一个ConnectionStringSettings类中,另一个选项被加载到一个MyOptions类中.该.GetSection方法获取appsettings.json文件的特定部分.再次,这是在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);
Run Code Online (Sandbox Code Playgroud)

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

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

public class ConnectionStringSettings
{
    public string DefaultConnection { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

private readonly MyOptions _myOptions;

public HomeController(IOptions<MyOptions > optionsAccessor)
{
    _myOptions = optionsAccessor.Value;
    var valueOfOpt1 = _myOptions.Option1;
}
Run Code Online (Sandbox Code Playgroud)

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

Microsoft文档中还提供了有关ASP.NET核心配置的更详细说明.