.NET Core: Inject AppSettings.json Values into PageModel or Controller

10/15/2019 6:49:33 PM

The following can be used to pull data from the appsettings.json file and inject the data into a Razor Page.

appsettings.json With EnvironmentVariables Section


{  
	"EnvironmentVariables":
	{
		"MySQL_Server": "127.0.0.1",
		"MySQL_Database": "my_db",
		"MySQL_Username": "root",
		"MySQL_Password": "password"
	}
}

Create EnvironmentVariables Class


public class EnvironmentVariables
{
	public string MySQL_Server { get; set; }
	public string MySQL_Database { get; set; }
	public string MySQL_Username { get; set; }
	public string MySQL_Password { get; set; }
}

Populate EnvironmentVariables in Startup.cs and Inject


var env_variables = new Models.EnvironmentVariables();
var config_section = Configuration.GetSection("EnvironmentVariables");

env_variables.MySQL_Server = config_section["MySQL_Server"];
env_variables.MySQL_Database = config_section["MySQL_Database"];
env_variables.MySQL_Username = config_section["MySQL_Username"];
env_variables.MySQL_Password = config_section["MySQL_Password"];

//inject variables
services.AddSingleton(env_variables);         

PageModel Injected


public class IndexModel : PageModel
{
	Models.EnvironmentVariables _Env_Variables = null;

	public IndexModel(Models.EnvironmentVariables env_variables)
	{
		this._Env_Variables = env_variables;
	}


	public void OnGet()
	{           
	}
}