不确定我在这里错过了什么,但我无法从我的应用程序设置中获得值。Json在我的。net核心应用程序。我有我的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总是空的。我是不是遗漏了什么?


当前回答

我发现用。net Core 3+最容易做到以下几点。我发现所有使用HostBuilders等的其他方法都有点啰嗦,而且可读性不强。这不是专门针对ASP的。但是你可以调整它…

这里有一个工作示例: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 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; }
}

创建一个helper类:

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

其他回答

这通常发生在vscode中,因为配置launch.json的方式不同。

基于这个答案,我不得不重新配置基本路径,配置正在搜索的DLL的路径,因为默认设置是可选的,很难在.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: web的抽象。Config, app.config和appsettings.json

    static SafeDictionary<string, string> _appSettings;

    public static SafeDictionary<string, string> AppSettings {
        get {
            if (_appSettings == null)
            {
                _appSettings = ConfigurationManager.AppSettings
                    .ToDictionary()
                    .ToSafe();

                BuildAppSettings( JsonAppSettings, "");

            }

            return _appSettings;
        }
    }


    static SafeDictionary<string, string> _connectionStrings;

    public static SafeDictionary<string, string> ConnectionStrings
    {
        get
        {
            if (_connectionStrings == null)
            {
                _connectionStrings = ConfigurationManager.ConnectionStrings
                    .Cast<ConnectionStringSettings>()
                    .ToDictionary(x => x.Name, x => x.ConnectionString)
                    .ToSafe();

                foreach (var jp in JsonAppSettings["ConnectionStrings"].Cast<JProperty>())
                    _connectionStrings.Add(jp.Name, jp.Value.ToString() );

            }

            return _connectionStrings;
        }
    }

https://github.com/bitministry/common

从Asp.net core 2.2到以上版本,你可以编写如下代码:

步骤1。创建一个AppSettings类文件。

这个文件包含一些帮助从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(配置);

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。从操作中读取配置值

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

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

结果如下:

点击查看结果

    public static void GetSection()
    {
        Configuration = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json")
            .Build();

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

    }

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

Startup.cs构造函数

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;

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

    }

public IConfiguration Configuration { get; }

json的内容

  {
  "Grandfather": {
    "Father": {
      "Child": "myvalue"
    }
  }