Create class like a class below
public class MyOptions
{
public MyOptions()
{
// Set default value, if you need it.
Key1 = "value1_from_ctor";
}
public string Key1 { get; set; }
public int Key2 { get; set; }
}
Then you need to add this code to your Startup class
public class Startup
{
// Some default code here
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
// Register the IConfiguration instance which MyOptions binds against.
services.Configure<MyOptions>(Configuration);
}
}
Then you could use it in your controllers in a way like presented below
public class TestController : Controller
{
private readonly MyOptions _optionsAccessor;
public TestController (IOptions<MyOptions> optionsAccessor)
{
_optionsAccessor = optionsAccessor.Value;
}
public IActionResult Index()
{
var key1 = _optionsAccessor.Key1 ;
var key2 = _optionsAccessor.Key1 ;
return Content($"option1 = {key1}, option2 = {key2}");
}
}