在aspnet5 / mvc6项目中,我使用配置构建器从appsettings.json读取设置:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddMvc();
}
但是,当我尝试从控制器访问服务时,不会调用该操作:
public IActionResult Index(IOptions<AppSettings> appSettings)
{
return View();
}
如果我删除了appSettings参数,则正确调用该操作。 我没有收到错误消息。我需要额外的套餐吗?目前我使用以下依赖项:
"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
}
答案 0 :(得分:1)
就像haim770评论一样,我需要在控制器构造函数中注入IOption。
public class HomeController : Controller
{
public HomeController(IOptions<AppSettings> appSettings)
{
//logic
}
}
答案 1 :(得分:1)
如果您想通过操作参数注入选项,则需要使用[FromServices]
修饰options参数:
public IActionResult Index([FromServices] IOptions<AppSettings> appSettings)
{
return View();
}
虽然它得到了肯定的支持,但通常最好使用构造函数注入,如haim770所示。