我正在尝试在ASP.NET Core MVC项目中使用配置变量.
@H_403_2@这是我到目前为止的地方:
@H_403_2@>创建了一个appsettings.json
>创建了一个AppSettings类
>现在我正在尝试将其注入到ConfigureServices上,但我的Configuration类无法识别或使用完整引用:“Microsoft.Extensions.Configuration”GetSection方法无法识别,即 @H_403_2@Configuration class not being recognized @H_403_2@GetSection method not being recognized @H_403_2@关于如何使用这个的任何想法?
>创建了一个AppSettings类
>现在我正在尝试将其注入到ConfigureServices上,但我的Configuration类无法识别或使用完整引用:“Microsoft.Extensions.Configuration”GetSection方法无法识别,即 @H_403_2@Configuration class not being recognized @H_403_2@GetSection method not being recognized @H_403_2@关于如何使用这个的任何想法?
解决方法
.NET Core中的整个配置方法非常灵活,但一开始并不明显.用一个例子来解释可能是最容易的:
@H_403_2@假设appsettings.json文件看起来像这样:
{ "option1": "value1_from_json","ConnectionStrings": { "DefaultConnection": "Server=,\\sql2016DEV;Database=DBName;Trusted_Connection=True" },"Logging": { "IncludeScopes": false,"LogLevel": { "Default": "Warning" } } }@H_403_2@要从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();@H_403_2@然后,您可以直接访问配置,但创建选项类来保存该数据更为全面,然后您可以将这些数据注入控制器或其他类.每个选项类都代表appsettings.json文件的不同部分. @H_403_2@在此代码中,连接字符串被加载到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);@H_403_2@这些是设置数据加载到的类.请注意属性名称如何与json文件中的设置配对:
public class MyOptions { public string Option1 { get; set; } } public class ConnectionStringSettings { public string DefaultConnection { get; set; } }@H_403_2@最后,您可以通过将OptionsAccessor注入控制器来访问这些设置,如下所示:
private readonly MyOptions _myOptions; public HomeController(IOptions<MyOptions > optionsAccessor) { _myOptions = optionsAccessor.Value; var valueOfOpt1 = _myOptions.Option1; }@H_403_2@通常,Core中的整个配置设置过程非常不同. Thomas Ardal在他的网站上有一个很好的解释:http://thomasardal.com/appsettings-in-asp-net-core/ @H_403_2@还有一个更详细的说明Configuration in ASP.NET Core in the Microsoft documentation.