【发布时间】:2018-02-14 16:56:15
【问题描述】:
我正在尝试添加一个 appsettings.json 并遵循了很多教程但仍然无法做到。
我创建 appsettings.json
{
"option1": "value1_from_json",
"ConnectionStrings": {
"DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
添加我的班级:
public class MyOptions
{
public string Option1 { get; set; }
}
public class ConnectionStringSettings
{
public string DefaultConnection { get; set; }
}
然后在我的 Startup.cs 上
public IConfiguration Configuration { get; set; }
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())
{
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
和:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped<IDataService<Sale>, DataService<Sale>>();
// add My services
// 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);
}
并且还将依赖注入到控制器构造函数中。
public class ForecastApiController : Controller
{
private IDataService<Sale> _SaleDataService;
private readonly MyOptions _myOptions;
public ForecastApiController(IDataService<Sale> service, IOptions<MyOptions> optionsAccessor)
{
_SaleDataService = service;
_myOptions = optionsAccessor.Value;
var valueOfOpt1 = _myOptions.Option1;
}
}
编辑: 问题是我得到红色下划线的配置
services.Configure<MyOptions>(Configuration);
错误 CS1503
参数 2:无法从 'Microsoft.Extensions.Configuration.IConfiguration' 转换为 'System.Action Exercise.Models.MyOptions
我知道有类似的问题解释了如何: ASP.NET Core MVC App Settings
但它对我不起作用
干杯
【问题讨论】:
-
如果有下划线,按 ctrl+。看看它告诉你什么。你错过了这条线吗?
IConfigurationRoot Configuration { get; } -
是的,现在我得到:错误 CS1503 参数 2:无法从 'Microsoft.Extensions.Configuration.IConfiguration' 转换为 'System.Action
' -
当我有括号或分号丢失或多余时,我会看到这种错误。
-
抱歉,我用关于您的评论的新错误消息编辑了问题
-
其实,我想我有个主意了。尝试在您的 appsettings 中添加一个小节,例如
{ "ConfigStrings": { "History" 14 } }。然后拨打services.Configure<MyOptions>(Configuration.GetSection("ConfigStrings"))
标签: asp.net-core