Reputation: 71
I am trying to read the appsettings.json file with the strongly type class and pass that as a parameter to controller. However its not working. Here is the code.
appsettings.json file:
{
"AppSettings": {
"ApplicationName": "TestApp"
}
}
AppSettings Class:
public class AppSettings
{
public string ApplicationName { get; set; }
}
Injecting in Startup Class:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddOptions();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
Controller:
public class ValuesController : Controller
{
private readonly IOptions<AppSettings> _appsettings;
public ValuesController(IOptions<AppSettings> appsettings)
{
_appsettings = appsettings;
}
[HttpGet]
public string Get()
{
return _appsettings.Options.ApplicationName;
}
}
The startup program is successfully getting executed. However, the controller constructor or default get method is not called.
It is working, If I remove the (IOptions appsettings) from the controller constructor.
What's wrong with my code.
Upvotes: 0
Views: 3017
Reputation: 2271
IOptions.Options was renamed to IOptions.Value in beta8. See this question.
Changing your Get action from:
return _appsettings.Options.ApplicationName;
to:
return _appsettings.Value.ApplicationName;
should fix that issue.
UPDATE 3/8/2016
The other issue I see here is that you're calling the Get
action the "default" action, but the default routing in ASP.Net Core looks for an Index
action on the controller.
You can configure the route in Startup.cs
to look for a Get
action by default instead of an Index
action by modifying the Configure
function to include something like this:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Get}/{id?}");
});
The default implmentation uses the template template: "{controller=Home}/{action=Index}/{id?}"
which is why it looks for an Index
action.
Your other options would be to change your Get
function to an Index
function, explicitly specify the Get
action in the url when you visit the site (ex. http://localhost/Values/Get), or specify the action name for the Get
method in your controller like this:
[HttpGet]
[ActionName("Index")]
public string Get()
{
return _appsettings.Value.ApplicationName;
}
Upvotes: 1