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

问题描述:

我想在我的ASP.NET Core MVC项目上使用配置变量。ASP.NET核心MVC应用程序设置

这是我走到这一步:

  1. 创建一个appsettings.json
  2. 创建一个AppSettings的类
  3. 现在我试图注入它的ConfigureServices,但我的配置类无法识别,或者在使用完整引用时:“Microsoft.Extensions.Configuration”GetSection方法无法识别,即

Configuration class not being recognized

GetSection method not being recognized

有关如何使用它的任何想法?

+0

请注意,没有MVC6,只有MVC1- 5。它现在被称为ASP.NET Core 1.x,从版本1开始讲清楚它不是MVC5的后继**,而是一个完全重写,它与MVC5 **和以前版本的ASP不兼容。 NET MVC – Tseng

.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(); 

然后你可以直接访问配置,但它的整洁创建选项班浩ld这些数据,然后你可以注入你的控制器或其他类。每个选项类代表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/

还有关于Configuration in ASP.NET Core in the Microsoft documentation的更详细的解释。

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

“Microsoft.Extensions.Options.ConfigurationExtensions”: “1.0.2”, “Microsoft.Extensions.Configuration.Json”: “1.1.1”