如何在Visual Studio代码中从appsettings.config文件添加和访问键值对?

时间:2019-06-21 10:40:38

标签: c# .net-core visual-studio-code app-config

我已经使用.net核心和Visual Studio代码上的sdk在控制台应用程序中编写了C#逻辑。我正在尝试添加配置文件以配置某些参数,但是,一旦创建了appsettings.json文件,便无法在代码中访问它。需要帮助来访问配置文件中的值。

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; }
    }
}

2 个答案:

答案 0 :(得分:1)

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": "*"
}

答案 1 :(得分:0)

尝试一下-

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"
}

enter image description here