[英]How to add and access key value pairs from appsettings.config file in visual studio code?
I have written my C# logic in a console application using the .net core and sdk on visual studio code. 我已经使用.net核心和Visual Studio代码上的sdk在控制台应用程序中编写了C#逻辑。 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. 我正在尝试添加配置文件以配置某些参数,但是,一旦创建了appsettings.json文件,便无法在代码中访问它。 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; }
}
}
HomeController.cs 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.json
{
"AppSettings": {
"Token": "T21pZC1NaXJ6YWVpWhithOutStar*"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
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 appsettings.json
{
"name": "appName"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.