从 .net 核心中的 appsettings.json 获取价值

Getting value from appsettings.json in .net core

不确定我在这里遗漏了什么,但我无法从我的 .net 核心应用程序中的 appsettings.json 获取值。我的 appsettings.json 为:

{
    "AppSettings": {
        "Version": "One"
    }
}

启动:

public class Startup
{
    private IConfigurationRoot _configuration;
    public Startup(IHostingEnvironment env)
    {
        _configuration = new ConfigurationBuilder()
    }
    public void ConfigureServices(IServiceCollection services)
    {
      //Here I setup to read appsettings        
      services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
    }
}

型号:

public class AppSettings
{
    public string Version{ get; set; }
}

控制器:

public class HomeController : Controller
{
    private readonly AppSettings _mySettings;

    public HomeController(IOptions<AppSettings> settings)
    {
        //This is always null
        _mySettings = settings.Value;
    }
}

_mySettings 始终为空。我在这里遗漏了什么吗?

程序和启动class

.NET 核心 2.x

您不需要在 Startup 构造函数中新建 IConfiguration。它的实现将由DI系统注入。

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();            
}

// Startup.cs
public class Startup
{
    public IHostingEnvironment HostingEnvironment { get; private set; }
    public IConfiguration Configuration { get; private set; }

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        this.HostingEnvironment = env;
        this.Configuration = configuration;
    }
}

.NET 核心 1.x

您需要告诉 Startup 加载应用程序设置文件。

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
    }
}

//Startup.cs
public class Startup
{
    public IConfigurationRoot Configuration { get; private set; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        this.Configuration = builder.Build();
    }
    ...
}

获取值

您可以通过多种方式获取您在应用设置中配置的值:

  • 使用ConfigurationBuilder.GetValue<T>
  • 的简单方法
  • 使用Options Pattern

假设您的 appsettings.json 看起来像这样:

{
    "ConnectionStrings": {
        ...
    },
    "AppIdentitySettings": {
        "User": {
            "RequireUniqueEmail": true
        },
        "Password": {
            "RequiredLength": 6,
            "RequireLowercase": true,
            "RequireUppercase": true,
            "RequireDigit": true,
            "RequireNonAlphanumeric": true
        },
        "Lockout": {
            "AllowedForNewUsers": true,
            "DefaultLockoutTimeSpanInMins": 30,
            "MaxFailedAccessAttempts": 5
        }
    },
    "Recaptcha": { 
        ...
    },
    ...
}

简单方法

您可以将整个配置注入 controller/class 的构造函数(通过 IConfiguration)并使用指定键获取所需的值:

public class AccountController : Controller
{
    private readonly IConfiguration _config;

    public AccountController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _config.GetValue<int>(
                "AppIdentitySettings:Password:RequiredLength"),
            RequireUppercase = _config.GetValue<bool>(
                "AppIdentitySettings:Password:RequireUppercase")
        };

        return View(vm);
    }
}

选项模式

如果您只需要应用程序设置中的一个或两个值,ConfigurationBuilder.GetValue<T> 非常有用。但是如果你想从应用程序设置中获取多个值,或者你不想在多个地方对这些键字符串进行硬编码,使用 Options Pattern 可能更容易。选项模式使用 classes 来表示 hierarchy/structure.

要使用选项模式:

  1. 定义 classes 来表示结构
  2. 注册那些classes绑定的配置实例
  3. IOptions<T> 注入到 controller/class 的构造函数中,你想在
  4. 上获取值

1。定义配置 classes 来表示结构

您可以使用 需要与应用设置中的键完全匹配的属性来定义 classes。 class 的名称不必与应用设置中的部分名称相匹配:

public class AppIdentitySettings
{
    public UserSettings User { get; set; }
    public PasswordSettings Password { get; set; }
    public LockoutSettings Lockout { get; set; }
}

public class UserSettings
{
    public bool RequireUniqueEmail { get; set; }
}

public class PasswordSettings
{
    public int RequiredLength { get; set; }
    public bool RequireLowercase { get; set; }
    public bool RequireUppercase { get; set; }
    public bool RequireDigit { get; set; }
    public bool RequireNonAlphanumeric { get; set; }
}

public class LockoutSettings
{
    public bool AllowedForNewUsers { get; set; }
    public int DefaultLockoutTimeSpanInMins { get; set; }
    public int MaxFailedAccessAttempts { get; set; }
}

2。注册配置实例

然后你需要在启动时在ConfigureServices()中注册这个配置实例:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
...

namespace DL.SO.UI.Web
{
    public class Startup
    {
        ...
        public void ConfigureServices(IServiceCollection services)
        {
            ...
            var identitySettingsSection = 
                _configuration.GetSection("AppIdentitySettings");
            services.Configure<AppIdentitySettings>(identitySettingsSection);
            ...
        }
        ...
    }
}

3。注入 IOptions

最后在controller/class上要获取值,需要通过构造函数注入IOptions<AppIdentitySettings>

public class AccountController : Controller
{
    private readonly AppIdentitySettings _appIdentitySettings;

    public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
    {
        _appIdentitySettings = appIdentitySettingsAccessor.Value;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
            RequireUppercase = _appIdentitySettings.Password.RequireUppercase
        };

        return View(vm);
    }
}

添加到 David Liang 对 Core 2.0 的回答 -

appsettings.json 文件链接到 ASPNETCORE_ENVIRONMENT 变量。

ASPNETCORE_ENVIRONMENT可以设置为任意值,但框架支持三个值:DevelopmentStagingProduction。如果未设置 ASPNETCORE_ENVIRONMENT,它将默认为 Production

对于这三个值,开箱即用地支持这些 appsettings.ASPNETCORE_ENVIRONMENT.json 文件 - appsettings.Staging.jsonappsettings.Development.jsonappsettings.Production.json

以上三个应用设置json文件可以用来配置多个环境

示例 - appsettings.Staging.json

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "MyConfig": "My Config Value for staging."
}

使用Configuration["config_var"]检索任何配置值。

public class Startup
{
    public Startup(IHostingEnvironment env, IConfiguration config)
    {
        Environment = env;
        Configuration = config;
        var myconfig = Configuration["MyConfig"];
    }

    public IConfiguration Configuration { get; }
    public IHostingEnvironment Environment { get; }
}

只需创建一个 AnyName.cs 文件并粘贴以下代码。

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace Custom
{
    static class ConfigurationManager
    {
        public static IConfiguration AppSetting { get; }
        static ConfigurationManager()
        {
            AppSetting = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("YouAppSettingFile.json")
                    .Build();
        }
    }
}

必须用您的文件名替换 YouAppSettingFile.json 文件名。
您的 .json 文件应如下所示。

{
    "GrandParent_Key" : {
        "Parent_Key" : {
            "Child_Key" : "value1"
        }
    },
    "Parent_Key" : {
        "Child_Key" : "value2"
    },
    "Child_Key" : "value3"
}

现在可以使用了。
不要忘记在您要使用的 class 中 Add Reference

using Custom;

检索值的代码。

string value1 = ConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"];
string value2 = ConfigurationManager.AppSetting["Parent_Key:Child_Key"];
string value3 = ConfigurationManager.AppSetting["Child_Key"];

我想最简单的方法是DI。进入 Controller 的示例。

// StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
    ...
    // for get appsettings from anywhere
    services.AddSingleton(Configuration);
}

public class ContactUsController : Controller
{
    readonly IConfiguration _configuration;

    public ContactUsController(
        IConfiguration configuration)
    {
        _configuration = configuration;

        // sample:
        var apiKey = _configuration.GetValue<string>("SendGrid:CAAO");
        ...
    }
}

在我的例子中,使用配置对象上的 Bind() 方法很简单。然后将对象作为单例添加到 DI 中。

var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);

Instruction 对象可以很复杂。

{  
 "InstructionSettings": {
    "Header": "uat_TEST",
    "SVSCode": "FICA",
    "CallBackUrl": "https://UATEnviro.companyName.co.za/suite/webapi/receiveCallback",
    "Username": "s_integrat",
    "Password": "X@nkmail6",
    "Defaults": {
    "Language": "ENG",
    "ContactDetails":{
       "StreetNumber": "9",
       "StreetName": "Nano Drive",
       "City": "Johannesburg",
       "Suburb": "Sandton",
       "Province": "Gauteng",
       "PostCode": "2196",
       "Email": "ourDefaultEmail@companyName.co.za",
       "CellNumber": "0833 468 378",
       "HomeNumber": "0833 468 378",
      }
      "CountryOfBirth": "710"
    }
  }

在 Startup class 的构造函数中,您可以使用注入的 IConfiguration 对象访问 appsettings.json 和许多其他设置:

Startup.cs构造函数

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;

        //here you go
        var myvalue = Configuration["Grandfather:Father:Child"];

    }

public IConfiguration Configuration { get; }

的内容appsettings.json

  {
  "Grandfather": {
    "Father": {
      "Child": "myvalue"
    }
  }
    public static void GetSection()
    {
        Configuration = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json")
            .Build();

        string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];

    }

我认为最好的选择是:

  1. 创建模型 class 作为配置架构

  2. 在DI注册: services.Configure(Configuration.GetSection("democonfig"));

  3. 从控制器中的 DI 获取模型对象的值:

    private readonly your_model myConfig;
    public DemoController(IOptions<your_model> configOps)
    {
        this.myConfig = configOps.Value;
    }
    

对于 ASP.NET Core 3.1,您可以遵循此指南:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

当您创建一个新的 ASP.NET Core 3.1 项目时,您将在 Program.cs 中有以下配置行:

Host.CreateDefaultBuilder(args)

这会启用以下功能:

  1. ChainedConfigurationProvider : 添加现有的 IConfiguration 作为 资源。默认配置情况下,添加主机 配置并将其设置为应用程序的第一个来源 配置。
  2. appsettings.json 使用 JSON 配置 提供商。
  3. appsettings.Environment.json 使用 JSON 配置 提供商。例如,appsettings.Production.json 和 appsettings.Development.json。
  4. 应用运行时的应用机密 开发环境。
  5. 环境变量使用Environment 变量配置提供程序。
  6. 命令行参数使用 命令行配置提供程序。

这意味着您可以注入 IConfiguration 并使用字符串键获取值,甚至是嵌套值。喜欢IConfiguration["Parent:Child"];

示例:

appsettings.json

{
  "ApplicationInsights":
    {
        "Instrumentationkey":"putrealikeyhere"
    }
}

WeatherForecast.cs

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var key = _configuration["ApplicationInsights:InstrumentationKey"];

        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

从 Asp.net core 2.2 到更高版本,您可以编写如下代码:

步骤 1. 创建 AppSettings class 文件。

此文件包含一些方法,可帮助通过键从 appsettings.json 文件中获取值。看起来像下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ReadConfig.Bsl
{
  public class AppSettings
  {
      private static AppSettings _instance;
      private static readonly object ObjLocked = new object();
      private IConfiguration _configuration;

      protected AppSettings()
      {
      }

      public void SetConfiguration(IConfiguration configuration)
      {
          _configuration = configuration;
      }

      public static AppSettings Instance
      {
          get
          {
              if (null == _instance)
              {
                  lock (ObjLocked)
                  {
                      if (null == _instance)
                          _instance = new AppSettings();
                  }
              }
              return _instance;
          }
      }

      public string GetConnection(string key, string defaultValue = "")
      {
          try
          {
              return _configuration.GetConnectionString(key);
          }
          catch
          {
              return defaultValue;
          }
      }

      public T Get<T>(string key = null)
      {
          if (string.IsNullOrWhiteSpace(key))
              return _configuration.Get<T>();
          else
              return _configuration.GetSection(key).Get<T>();
      }

      public T Get<T>(string key, T defaultValue)
      {
          if (_configuration.GetSection(key) == null)
              return defaultValue;

          if (string.IsNullOrWhiteSpace(key))
              return _configuration.Get<T>();
          else
              return _configuration.GetSection(key).Get<T>();
      }

      public static T GetObject<T>(string key = null)
      {
          if (string.IsNullOrWhiteSpace(key))
              return Instance._configuration.Get<T>();
          else
          {
              var section = Instance._configuration.GetSection(key);
              return section.Get<T>();
          }
      }

      public static T GetObject<T>(string key, T defaultValue)
      {
          if (Instance._configuration.GetSection(key) == null)
              return defaultValue;

          if (string.IsNullOrWhiteSpace(key))
              return Instance._configuration.Get<T>();
          else
              return Instance._configuration.GetSection(key).Get<T>();
      }
  }
}

步骤 2.AppSettings 对象的初始配置

我们需要在应用程序启动时声明并加载appsettings.json文件,加载AppSettings对象的配置信息。我们将在 Startup.cs 文件的构造函数中完成这项工作。 请注意行 AppSettings.Instance.SetConfiguration(Configuration);

public Startup(IHostingEnvironment evm)
{
    var builder = new ConfigurationBuilder()
      .SetBasePath(evm.ContentRootPath)
      .AddJsonFile("appsettings.json", true, true)
      .AddJsonFile($"appsettings.{evm.EnvironmentName}.json", true)
      .AddEnvironmentVariables();
    Configuration = builder.Build(); // load all file config to Configuration property 
    AppSettings.Instance.SetConfiguration(Configuration);       
}

好的,现在我有一个 appsettings.json 文件,其中包含一些键,如下所示:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ConnectionString": "Data Source=localhost;Initial Catalog=ReadConfig;Persist Security Info=True;User ID=sa;Password=12345;"
  },
  "MailConfig": {
    "Servers": {
      "MailGun": {
        "Pass": "65-1B-C9-B9-27-00",
        "Port": "587",
        "Host": "smtp.gmail.com"
      }
    },
    "Sender": {
      "Email": "example@gmail.com",
      "Pass": "123456"
    }
  }
}

步骤 3. 从操作中读取配置值

我在家庭控制器中演示了一个动作,如下所示:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        var connectionString = AppSettings.Instance.GetConnection("ConnectionString");
        var emailSender = AppSettings.Instance.Get<string>("MailConfig:Sender:Email");
        var emailHost = AppSettings.Instance.Get<string>("MailConfig:Servers:MailGun:Host");

        string returnText = " 1. Connection String \n";
        returnText += "  " +connectionString;
        returnText += "\n 2. Email info";
        returnText += "\n Sender : " + emailSender;
        returnText += "\n Host : " + emailHost;

        return Content(returnText);
    }
}

下面是结果:

Click to see result

假设您在 appsettings.json 中有这样的值。

  "MyValues": {
    "Value1": "Xyz"
  }

方法一:无依赖注入

在 .cs 文件中:

static IConfiguration conf = (new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build());
public static string myValue1= conf["MyValues:Value1"].ToString();

方法二:使用依赖注入(推荐)

在 Startup.cs 文件中:

public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
     Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
     ...
     services.AddServices(Configuration);
}

在您的控制器中:

public class TestController : ControllerBase
{
    private string myValue1 { get; set; }
    public TestController(IConfiguration configuration)
    {
         this.myValue1 = configuration.GetValue<string>("MyValues:Value1");
    }
}

.NET核心3.X

无需创建新模型并在 Startup.cs 中设置。

控制器 添加新包 - 使用 Microsoft.Extensions.Configuration;

public class HomeController : Controller
{
    private readonly IConfiguration _mySettings;

    public HomeController (IConfiguration mySettings)
    {
         _mySettings= mySettings;
    }
 
    //ex: you can get value on below function 
    public IEnumerable<string> Get()
    {
        var result = _config.GetValue<string>("AppSettings:Version"); // "One"
        return new string[] { result.ToString() };
    }
}
  1. 像这样在此处添加所需的密钥。在这种情况下,它的 SecureCookies:

  1. 在startup.cs中添加构造函数

     public Startup(IConfiguration configuration)
     {
         Configuration = configuration;
    
     }
     public IConfiguration Configuration { get; }
    
  2. 使用配置["SecureCookies"]访问设置

这往往发生在 上,正如我假设的那样,因为 launch.json.

的配置方式

基于 I had to reconfigure the base path the configuration is being searched for to that of DLL's path,并且由于默认设置是可选的,因此很难在 .net core 3.1 和 net 5.0 应用程序上进行追踪。这是我重新配置的方式

Program.cs:

using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace API
{
    public class Program
    {
        public static int Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            return 0;
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(c =>
            {
                var codeBase = Assembly.GetExecutingAssembly().Location;
                var uri = new UriBuilder(codeBase);
                var path = Uri.UnescapeDataString(uri.Path);
                var assembyDirectory = Path.GetDirectoryName(path);
                c.SetBasePath(assembyDirectory);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            ;
        }
    }
}

我可以正常访问 Startup.cs 中的配置:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model;

namespace API
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var myOptions = Configuration.To<ApiConfig>();
            services.AddAuthentication(myOptions.Secret);
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}

我发现使用 .NET Core 3+ 执行以下操作最简单。我发现使用 HostBuilders 等的所有其他方法都有些冗长且可读性差。这不是专门针对 ASP.Net 但您可以对其进行调整...

这里有一个工作示例:https://github.com/NotoriousPyro/PyroNexusTradingAlertBot/blob/develop/PyroNexusTradingAlertBot/Program.cs

创建 json:

{
"GlobalConfig": {
    "BlacklistedPairs": [ "USD", "USDT", "BUSD", "TUSD", "USDC", "DAI", "USDK" ]
},
"CoinTrackingConfig": {
    "Cookie1": "",
    "Cookie2": "",
    "ApiKey": "",
    "ApiSecret": "",
    "UpdateJobs": [
    {
        "Name": "Binance",
        "Path": "binance_api",
        "JobId": 42202
    },
    {
        "Name": "Bitfinex",
        "Path": "bitfinex_api",
        "JobId": 9708
    }
    ]
},
"DiscordConfig": {
    "BotToken": ""
}
}

为 json 个对象创建 class:

class GlobalConfig
{
    public string[] BlacklistedPairs { get; set; }
}
class CoinTrackingConfig
{
    public string Cookie1 { get; set; }
    public string Cookie2 { get; set; }
    public string ApiKey { get; set; }
    public string ApiSecret { get; set; }
    public List<CoinTrackingUpdateJobs> UpdateJobs { get; set; }
}

class CoinTrackingUpdateJobs
{
    public string Name { get; set; }
    public string Path { get; set; }
    public int JobId { get; set; }
}

class DiscordConfig
{
    public string BotToken { get; set; }
}

创建助手class:

private class Config
{
    private IConfigurationRoot _configuration;
    public Config(string config) => _configuration = new ConfigurationBuilder()
            .AddJsonFile(config)
            .Build();

    public T Get<T>() where T : new()
    {
        var obj = new T();
        _configuration.GetSection(typeof(T).Name).Bind(obj);
        return obj;
    }
}

服务提供者选项和服务构造函数:

public class DiscordServiceOptions
{
    public string BotToken { get; set; }
}

public DiscordService(IOptions<DiscordServiceOptions> options, ILogger<DiscordService> logger)
{
    _logger = logger;
    _client = new DiscordSocketClient();
    _client.Log += Log;
    _client.Ready += OnReady;
    _client.Disconnected += OnDisconnected;
    _client.LoginAsync(TokenType.Bot, options.Value.BotToken);
    _client.StartAsync();
}

像这样初始化它(将配置传递给服务提供者 - 构建服务时将传递 IOptions):

static async Task Main(string[] args)
{
    var _config = new Config("config.json");

    var globalConfig = config.Get<GlobalConfig>();
    var coinTrackingConfig = config.Get<CoinTrackingConfig>();
    var discordConfig = config.Get<DiscordConfig>();

    _services = new ServiceCollection()
        .AddOptions()
        .Configure<DiscordServiceOptions>(options =>
        {
            options.BotToken = discordConfig.BotToken;
        })
        .AddSingleton<IDiscordService, DiscordService>()
        .AddLogging(logging =>
        {
            logging.SetMinimumLevel(LogLevel.Trace);
            logging.AddNLog(new NLogProviderOptions
            {
                CaptureMessageTemplates = true,
                CaptureMessageProperties = true
            });
        })
        .BuildServiceProvider();
}

在我的例子中,我从头开始创建了所有内容,appsettings.json 也根本没有加载。经过一些调试,我发现文件并没有复制到“目标文件夹”。

要修复它,我只需设置正确的文件属性即可。

看起来像这样:

我在 WPF (.NET Framework 5.0) 中遇到了类似的问题

我所要做的就是注册它。

services.AddSingleton<IConfiguration>(_configuration);

配置本身是这样配置的(在 App.xaml.cs 中):

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

_configuration = builder.Build();
  1. appsetting.json

{   
  "Settings": {      
    "ProjectName": "Sample Project"   
  }
}
  1. 用相同的 属性 名称定义一个 class:
 public class Settings
 {
     public string ProjectName { get; set; }  
 }
  1. Startup.cs中添加配置:
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<Settings>(Configuration.GetSection("Settings")); 
}
  1. 注入控制器:
public class TestController : Controller
{
    private readonly Settings _settings;       
    
    public TestController(IOptions<Settings> settings)
    {
         _settings = settings.Value;
    }
       
    [AllowAnonymous]
    public async Task<IActionResult> test()
    {
        var _projectname = _settings.ProjectName;
                
        return View();
    }
}

我只是创建了一个静态 class 并在 Startup.cs

中为其设置了一个配置变量
public static class GlobalConfig { 
    public static IConfiguration config { get; set; } 
}

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        GlobalConfig.config = configuration;

    }
}

然后在任何地方使用它:

var keyVal = GlobalConfig.config["key"];

似乎是访问配置文件并使其随处可用的最简单方法。

添加到 Abishek 的回答:

如果要将值导入静态 class,则只需使用(ReSharper 推荐):

static IConfiguration conf = (JsonConfigurationExtensions.AddJsonFile(new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()), "appsettings.json").Build());

private static string AuthorizationServiceURL { get; } = conf["ServiceUrls:AuthorizationUrl"];

// appsettings.json
{
  "ServiceUrls": {
    "AuthorizationUrl": "https://example.com/authorize"
  } 
}

花了一个小时试图解决同样的问题,我的解决方案是在 csproj

中为 appconfig.json 添加 PreserveNewest/CopyAlways
<None Update="appsettings.json">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>