从appsettings获取值。.net core中的Json

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

571743 次浏览

程序与启动课程

ASP。NET Core 6.x

ASP。NET Core 6。x在Program类中带来了另一个大的变化:

  • 如果您选择使用顶级语句,则没有Program.Main()样板
  • 隐式使用指令
  • 没有Startup类,因为所有内容都在Program文件中
  • 引入WebApplicationWebApplicationBuilder

有人说,这些变化有利于新人学习ASP。净的核心。我的感觉正好相反。我认为ProgramStartup的分离更有意义,至少对我来说。

无论如何……

这是Program.cs看起来的样子:

// Program.cs
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);


builder.Services.AddControllersWithViews();


var app = builder.Build();


if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/errors");
app.UseHsts();
}


app.UseHttpsRedirection();
app.UseStaticFiles();


app.UseRouting();


app.UseAuthorization();


app.MapControllerRoute(
name: "areaRoute",
pattern: "{area:exists}/{controller=home}/{action=index}/{id?}");
            

app.MapControllerRoute(
name: "default",
pattern: "{controller=home}/{action=index}/{id?}");


app.Run();
}
}

你可以看出WebApplication.CreateBuilder()builder.Build()之间的部分是旧的ConfigureServices(IServiceCollection services)用来做的。而app.Run()之前的部分是Startup中的旧Configure()所做的。

最重要的是,IConfiguration被注入到管道中,所以你可以在你的控制器上使用它。

ASP。NET Core 3。X至5

ASP。NET Core 3。X带来了一些变化,试图支持其他方法,如worker services,所以它用更通用的主机构建器取代了web主机:

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


public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
};
}
}

Startup类看起来非常类似于2。不过是X版本。

ASP。NET Core 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;
}
}

ASP。NET Core 1.x

你需要告诉Startup加载appsettings文件。

// 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": {
...
},
...
}

简单的方法

你可以将整个配置注入到你的控制器/类的构造函数中(通过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>工作得很好。但如果你想从应用程序设置中获得多个值,或者你不想在多个地方硬编码这些键字符串,使用选择模式可能更容易。选项模式使用类来表示层次结构/结构。

使用选项模式:

  1. 定义类来表示结构
  2. 注册这些类绑定到的配置实例
  3. IOptions<T>注入到你想获取值的控制器/类的构造函数中

1. 定义配置类来表示结构

你可以在应用程序设置中定义具有需要完全匹配键的属性的类。类的名称不必与应用设置中的section名称匹配:

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

ASP。NET Core 6.x

由于我在开头提到的ASP。NET Core 6。x,你需要绑定该section并将其添加到DI,如下所示:

// Program.cs
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);


builder.Services.AddControllersWithViews();


builder.Services.Configure<AppIdentitySettings>(
builder.Configuration.GetSection("AppIdentitySettings")
);


var app = builder.Build();


...


app.Run();
}
}

你可以阅读更多关于在这里

3.注入IOptions

最后,在你想获取值的控制器/类上,你需要通过构造函数注入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的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();
}
}
}
< p > 必须替换YouAppSettingFile。Json文件名与您的文件名。 < br > 你的.json文件应该如下所示
{
"GrandParent_Key" : {
"Parent_Key" : {
"Child_Key" : "value1"
}
},
"Parent_Key" : {
"Child_Key" : "value2"
},
"Child_Key" : "value3"
}

现在你可以使用它了 不要忘记在你想要使用的类中添加引用

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。一个进入控制器的例子。

// 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");
...
}
}

在我的例子中,它就像在Configuration对象上使用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类的构造函数中,可以访问appsettings。json和使用注入的IConfiguration对象的许多其他设置:

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. 创建一个模型类作为配置模式

  2. DI寄存器: services.Configure (Configuration.GetSection(“democonfig”));< / p > < /李>
  3. 从控制器的DI中获取模型对象的值:

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

ASP。NET Core 3.1你可以遵循以下指南:

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

当您创建一个新的ASP。在asp.net Core 3.1项目中,你将在Program.cs中有如下的配置行:

Host.CreateDefaultBuilder(args)

这将启用以下功能:

  1. ChainedConfigurationProvider:添加一个现有的IConfiguration 源。默认情况下,添加主机 配置并将其设置为应用程序的第一个源 配置。李< / > <李> appsettings。使用json配置 提供者。李< / > <李> appsettings.Environment。使用json配置 提供者。例如,appsettings.Production.json和 appsettings.Development.json。李< / >
  2. 当应用程序运行在 开发环境。李< / >
  3. 环境变量 变量配置提供程序。李< / >
  4. 使用 命令行配置提供程序

这意味着你可以注入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类文件。

这个文件包含一些帮助从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。从操作中读取配置值

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

结果如下:

点击查看结果

假设在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 core 3。X

不需要创建新的模型并在Startup.cs中设置。

< p >控制器 添加新的包- using 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. 像这样在这里添加所需的键。在这种情况下,它的securecookie:

在这里添加所需的键,就像这样。在这种情况下,它的SecureCookies

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

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

正如我假设的那样,这往往发生在上,因为配置launch.json的方式不同。

基于这个答案,我不得不重新配置基本路径的配置正在搜索的DLL的路径,由于默认设置是可选的,很难在.net核心3.1 &以下是我如何重新配置的

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的。但是你可以调整它…

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

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

为了解决这个问题,我只需要设置正确的文件属性。

它是这样的:

enter image description here

我在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. 定义一个具有相同属性名的类:
 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();
}
}

我只是创建了一个静态类,并在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"];

似乎是访问配置文件并使其在任何地方可用的最简单的方法。

亚比谢克的回答是:

如果你想将值导入到静态类中,那么只需使用(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"
}
}

花了一个小时试图解决同样的问题,我的解决方案是为appconfig添加PreserveNewest/CopyAlways。csproj中的Json

<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

这里是一个关于。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

如果以上解决方案没有帮助,您可以参考此链接。对我来说,使用IConfigureNamedOptions支持命名选项工作!你可能还会发现其他方法可能对你有帮助。

使用IConfigureNamedOptions支持命名选项