ASP.NET Core MVC 应用程序设置

6

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

目前为止,我已经:

  1. 创建了一个appsettings.json文件
  2. 创建了一个AppSettings类
  3. 现在我正在尝试将其注入到ConfigureServices中,但是我的Configuration类要么无法识别,要么使用完整引用“Microsoft.Extensions.Configuration”时无法识别GetSection方法,即:

未能识别Configuration类

未能识别GetSection方法

有什么想法如何使用它吗?


请注意,没有MVC6,只有MVC1-5。现在它被称为ASP.NET Core 1.x,从版本1开始,以明确表明它不是MVC5的继承者,而是一个完全重写的版本,与MVC5和之前版本的ASP.NET MVC不兼容 - Tseng
2个回答

9

.NET Core的整个配置方法非常灵活,但起初并不明显。最好通过示例来解释:

假设有一个类似下面这样的appsettings.json文件:

{
  "option1": "value1_from_json",

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

要从appsettings.json文件中获取数据,首先需要在Startup.cs中设置ConfigurationBuilder,如下所示:
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类来保存这些数据,并将其注入到控制器或其他类中。每个Options类代表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);

以下是设置数据加载到的类。请注意属性名称与json文件中的设置配对:

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

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

最后,您可以通过将OptionsAccessor注入控制器来访问这些设置,如下所示:
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/ 此外,Microsoft文档中还有更详细的关于ASP.NET Core中配置的解释
NB:这在Core 2中都有一些改变,我需要重新查看上面的一些答案,但同时,Ibrahim Šuta编写的Coding Blast条目是一个具有丰富示例的优秀介绍。
NB No. 2: 使用上述方法可能会犯一些易错的配置错误,如果出现问题可以参考这个答案

1

tomRedox的回答非常有帮助 - 谢谢。 此外,我已将以下引用更改为以下版本以使其正常工作。

"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.2", "Microsoft.Extensions.Configuration.Json": "1.1.1"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接