Reputation: 11
I have written my C# logic in a console application using the .net core and sdk on visual studio code. I'm trying to add a config file to configure certain parameters, however, once I create the appsettings.json file, I'm unable to access it in the code. Need help to access the values from config file.
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
var appSettings = new Config();
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddEnvironmentVariables() //This line doesnt compile
.AddJsonFile("appsettings.json", true, true)
.Build();
config.Bind(appSettings); //This line doesnt compile
Console.WriteLine("Hello World!");
Console.WriteLine($" Hello {appSettings.name} !");
}
}
public class Config
{
public string name{ get; set; }
}
}
Upvotes: 1
Views: 7938
Reputation: 524
Try this -
using System;
using Microsoft.Extensions.Configuration;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
var appSettings = new Config();
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", true, true)
.Build();
config.Bind(appSettings);
Console.WriteLine($" Hello {appSettings.name} !");
}
}
public class Config
{
public string name{ get; set; }
}
}
appsettings.json
{
"name": "appName"
}
Upvotes: -1
Reputation: 53
HomeController.cs
public class HomeController : Controller {
private readonly IConfiguration _config;
public HomeController(IConfiguration config) { _config = config; }
public IActionResult Index() {
Console.WriteLine(_config.GetSection("AppSettings:Token").Value);
return View();
}
}
appsettings.json
{
"AppSettings": {
"Token": "T21pZC1NaXJ6YWVpWhithOutStar*"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Upvotes: 2