我正在尝试在我的 ASP.NET Core MVC 项目中使用配置变量。
这是我到目前为止的地方:
Configuration class not being recognized
GetSection method not being recognized
关于如何使用它的任何想法?
最佳答案
.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 文件中获取数据,您首先需要设置
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();
然后您可以直接访问配置,但是创建选项类来保存该数据会更简洁,然后您可以将其注入(inject) Controller 或其他类。这些选项类中的每一个都代表 appsettings.json 文件的不同部分。
在这段代码中,连接字符串被加载到
ConnectionStringSettings
中。类和另一个选项加载到 MyOptions
类(class)。 .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 注入(inject) Controller 来访问这些设置,如下所示:
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还有更详细的解释.
注意:这一切在 Core 2 中都发生了一些变化,我需要重新审视上面的一些答案,但与此同时 this Coding Blast entry by Ibrahim Šuta是一个很好的介绍,有很多例子。
NB No. 2:上面有很多容易犯的配置错误,看看this answer如果它不适合你。
关于asp.net-core - ASP.NET Core MVC 应用设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448993/