grokky grokky - 1 month ago 10
ASP.NET (C#) Question

ASP.NET Core strongly-typed options from appsettings.json

There have been many changes to ASP.NET Core's "options" service. I'm using the latest version, and none of the tutorials and samples work anymore.

To keep it simple, I created a new ASP.NET Core web app, using Visual Studio's templates.

My

appsettings.json
contains:

"MyConfig": {
"Foo": "Bar"
}


My strongly-typed config object:

public class MyConfig {
public string Foo;
}


My
Startup.ConfigureServices
contains:

services.AddOptions();
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
//services.Configure<MyConfig>(opts => Configuration.GetSection("MyConfig").Bind(opts)); // I also tried this


My
HomeController
contains:

public class HomeController : Controller {

private readonly MyConfig _myConfig;

public HomeController(IOptions<MyConfig> myConfig) {
_myConfig = myConfig.Value;
}

public IActionResult Index() {
return Content(_myConfig.Foo); // Foo is null
}

}


And my
project.json
contains:

"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
//"Microsoft.Extensions.Configuration.Binder": "1.0.0", // I also tried this


But the
MyConfig.Foo
object is always
null
.

Answer

I'm doing very similar and it works for me. I suggest try adding a get;set; on your Foo field to make it a propertry, ie

public string Foo { get; set; } 

since that is one difference I see in your code

Comments