In an aspnet5/mvc6 project I use the configuration builder to read the settings from 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();
}
However, when I try to access the service from a controller, the action is not being called:
public IActionResult Index(IOptions<AppSettings> appSettings)
{
return View();
}
If I remove the appSettings parameter the action is being called correctly. I don't get an error message. Do I need additional packages? Currently I'm using the following dependencies:
"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"
}
Like haim770 commented I needed to inject IOption in the controller constructor.
public class HomeController : Controller
{
public HomeController(IOptions<AppSettings> appSettings)
{
//logic
}
}
If you want to inject your options through the action parameters, you need to decorate your options parameter with [FromServices]
:
public IActionResult Index([FromServices] IOptions<AppSettings> appSettings)
{
return View();
}
Though it's definitely supported, it's usually better to use constructor injection, as suggested by haim770.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.