如何使用 .NET Core 在控制台应用程序中从 appsettings.json 获取值?
How to get values from appsettings.json in a console application using .NET Core?
我正在使用 .NET Core 3.1 创建一个控制台应用程序,我想要一个应用程序设置 json 来加载所有
environment, paths, variables,... 在开始执行时,然后从其他库 classes 中获取值。
我用应用程序设置 json 中包含的数据创建了一个 'Settings' class。
这是我在教程中已经看到的,但我无法获得任何价值。
//Start.cs
public class Startup
{
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();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
}
//Settings.cs
public class Settings
{
public ConnectionStrings ConnectionStrings { get; set; }
public Logging Logging { get; set; }
public AppSettings AppSettings { get; set; }
...
//A class to use it in other lib
public class Extractor
{
private readonly IConfiguration _configuration;
public Extractor(IConfiguration configuration) : this()
{
_configuration = configuration;
Init();
}
public void Init()
{
// Extractor:Min is a variable included in appsettings.json
Min = _configuration.GetValue<int>("Extractor:Min")
}
我无法创建正确的 Main,因为我不知道如何初始化所有内容...我缺少什么?我想我一直在绕圈子做一些简单的事情。提前致谢!
注意:我需要从另一个库 class 中获取这些变量,而不是在 Main 中。我不知道如何在其他 class 中初始化 'configuration' 以便使用它。谢谢
您的示例混合了一些希望托管您的代码的 ASP NET Core 方法。要最低限度地解决从 JSON 配置获取选项或设置的问题,请考虑以下事项:
一个 config.json
文件,设置为“复制到输出目录”,以便它包含在构建中:
{
"MyFirstClass": {
"Option1": "some string value",
"Option2": 42
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 42
}
}
下面的方法将从 JSON 文件加载内容,然后将内容绑定到两个强类型 options/settings 类,这比 going value 更清晰- 按值:
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
// NuGet packages:
// Microsoft.Extensions.Configuration.Binder
// Microsoft.Extensions.Configuration.Json
namespace SampleConsole
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: false);
IConfiguration config = builder.Build();
var myFirstClass = config.GetSection("MyFirstClass").Get<MyFirstClass>();
var mySecondClass = config.GetSection("MySecondClass").Get<MySecondClass>();
Console.WriteLine($"The answer is always {myFirstClass.Option2}");
}
}
public class MyFirstClass
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}
public class MySecondClass
{
public string SettingOne { get; set; }
public int SettingTwo { get; set; }
}
}
我在使用 .NET Core 时遇到了同样的问题,我发现这个解决方案运行良好:
- 我有这个appsettings.json
{
"App":
{
"LoginCredentials":
{
"ClientId": "xxx",
"ClientSecret": "xxx",
"TenantId": "xxx"
},
"DataBase":
{
"PathToDatabases": "xxx"
},
"General":
{
"PathToLogFiles": "xxx"
}
}
}
- 我创建了一个classAppSettingsHandler.cs
public class AppSettingsHandler
{
private string _filename;
private AppSettings _config;
public AppSettingsHandler(string filename)
{
_filename = filename;
_config = GetAppSettings();
}
public AppSettings GetAppSettings()
{
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile(_filename, false, true)
.Build();
return config.GetSection("App").Get<AppSettings>();
}
}
- 那么你需要一个 AppSettings 的“模型”class:
public class AppSettings
{
public LoginCredentialsConfiguration LoginCredentials { get; set; }
public DatabaseConfiguration DataBase { get; set; }
public GeneralConfiguration General { get; set; }
}
和每个包含的子class的模型class,我在这里只举例说明一个:
public class LoginCredentialsConfiguration
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string TenantId { get; set; }
}
- 在您的 Program.cs class 中,您现在可以像这样从 appsettings.json 中获取参数:
var aH = new AppSettingsHandler("appsettings.json");
var aS = aH.GetAppSettings();
var myPath = aS.DataBase.PathToDatabases;
当然,您可以调整该代码,使其符合您的要求,即。即,您必须定义自己的 classes 和 subclasses,当然您也可以通过获取 appsettings.json 的其他部分来扩展 AppSettingsHandler.cs。
很有帮助!
- appsettings.json(添加appsettings.json后,转到属性并将文件标记为复制到out目录)
{
"ConnectionString": "Server=localhost;Database=tempDB;Uid=<dbUserName>;Pwd=<dbPassword>",
"Smtp": {
"Host": "smtp.gmail.com",
"Port": "587",
"Username": "<YourGmailUserName>",
"Password": "<YourGmailPassword>",
"From": "Your Name"
}
}
2.package 需要
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Json
- program.cs
using System;
using Microsoft.Extensions.Configuration;
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true);
var config = builder.Build();
var connectionString = config["ConnectionString"];
var emailHost = config["Smtp:Host"];
Console.WriteLine($"Connection String is: {connectionString}");
Console.WriteLine($"Email Host is: {emailHost}");
Console.ReadLine();
}
}
开始使用 Visual Studio 2022 和 .net 6。
- 创建一个新的控制台项目。
- 向项目添加一个 appsettings.json 文件。
- 右键单击 select 属性并确保将其复制到输出目录。
将文件编辑成如下所示。
{
"ConnectionString": "Server=localhost;Database=tempDB;Uid=<dbUserName>;Pwd=<dbPassword>",
"Smtp": {
"Host": "smtp.gmail.com",
"From": "Your Name"
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 82
}
}
编辑您的项目 csproj 文件以包含 Microsoft.Extensions.Configuration and its json counter part 包。见下文,同时注意 appsettings.json 文件。
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.json" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
最后,您的 program.cs 文件将如下所示。
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
var builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true);
var config = builder.Build();
var connectionString = config["ConnectionString"];
var emailHost = config["Smtp:Host"];
Console.WriteLine($"Connection String is: {connectionString}");
Console.WriteLine($"Email Host is: {emailHost}");
var settingTwo = config["MySecondClass:SettingOne"];
Console.WriteLine(settingTwo);
我试过以下方法,效果很好。
1- 将您的 launchSettings.json 添加到 Properties 文件夹下的项目.
2- 将 appsettings 文件添加到每个环境的项目中。
3- 将 appsettings 文件添加到 .csproj 中,如下所示。
4-然后你可以通过下面的代码根据环境注入并到达读取appsettings文件的IConfiguration。
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.{environment}.json")
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
var serviceProvider = new ServiceCollection()
.AddSingleton<IConfiguration>(configuration)
.BuildServiceProvider();
var configurationInstance = serviceProvider.GetService<IConfiguration>();
launchSettings.json
{
"profiles": {
"YourProject": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "DEV"
}
}
}
}
您应该在 .csproj 文件中添加您的 appSettings 文件
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="6.3.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.DEV.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.Production.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.QA.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
你可以在任何地方注入它
public class ConnectionService
{
private readonly IConfiguration _configuration;
public ConnectionService(IConfiguration configuration)
{
_configuration = configuration;
}
}
我正在使用 dotnet 6。
您只需要在主机上调用 CreateDefaultBuilder。
await Host
.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services
.AddHostedService<ConsoleHostedService>();
})
.RunConsoleAsync();
其中 ConsoleHostedService 实现 IHostedService。
通过调用 ConfigureServices 它会做你需要的。
我正在使用 .NET Core 3.1 创建一个控制台应用程序,我想要一个应用程序设置 json 来加载所有 environment, paths, variables,... 在开始执行时,然后从其他库 classes 中获取值。 我用应用程序设置 json 中包含的数据创建了一个 'Settings' class。 这是我在教程中已经看到的,但我无法获得任何价值。
//Start.cs
public class Startup
{
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();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
}
//Settings.cs
public class Settings
{
public ConnectionStrings ConnectionStrings { get; set; }
public Logging Logging { get; set; }
public AppSettings AppSettings { get; set; }
...
//A class to use it in other lib
public class Extractor
{
private readonly IConfiguration _configuration;
public Extractor(IConfiguration configuration) : this()
{
_configuration = configuration;
Init();
}
public void Init()
{
// Extractor:Min is a variable included in appsettings.json
Min = _configuration.GetValue<int>("Extractor:Min")
}
我无法创建正确的 Main,因为我不知道如何初始化所有内容...我缺少什么?我想我一直在绕圈子做一些简单的事情。提前致谢! 注意:我需要从另一个库 class 中获取这些变量,而不是在 Main 中。我不知道如何在其他 class 中初始化 'configuration' 以便使用它。谢谢
您的示例混合了一些希望托管您的代码的 ASP NET Core 方法。要最低限度地解决从 JSON 配置获取选项或设置的问题,请考虑以下事项:
一个 config.json
文件,设置为“复制到输出目录”,以便它包含在构建中:
{
"MyFirstClass": {
"Option1": "some string value",
"Option2": 42
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 42
}
}
下面的方法将从 JSON 文件加载内容,然后将内容绑定到两个强类型 options/settings 类,这比 going value 更清晰- 按值:
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
// NuGet packages:
// Microsoft.Extensions.Configuration.Binder
// Microsoft.Extensions.Configuration.Json
namespace SampleConsole
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: false);
IConfiguration config = builder.Build();
var myFirstClass = config.GetSection("MyFirstClass").Get<MyFirstClass>();
var mySecondClass = config.GetSection("MySecondClass").Get<MySecondClass>();
Console.WriteLine($"The answer is always {myFirstClass.Option2}");
}
}
public class MyFirstClass
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}
public class MySecondClass
{
public string SettingOne { get; set; }
public int SettingTwo { get; set; }
}
}
我在使用 .NET Core 时遇到了同样的问题,我发现这个解决方案运行良好:
- 我有这个appsettings.json
{
"App":
{
"LoginCredentials":
{
"ClientId": "xxx",
"ClientSecret": "xxx",
"TenantId": "xxx"
},
"DataBase":
{
"PathToDatabases": "xxx"
},
"General":
{
"PathToLogFiles": "xxx"
}
}
}
- 我创建了一个classAppSettingsHandler.cs
public class AppSettingsHandler
{
private string _filename;
private AppSettings _config;
public AppSettingsHandler(string filename)
{
_filename = filename;
_config = GetAppSettings();
}
public AppSettings GetAppSettings()
{
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile(_filename, false, true)
.Build();
return config.GetSection("App").Get<AppSettings>();
}
}
- 那么你需要一个 AppSettings 的“模型”class:
public class AppSettings
{
public LoginCredentialsConfiguration LoginCredentials { get; set; }
public DatabaseConfiguration DataBase { get; set; }
public GeneralConfiguration General { get; set; }
}
和每个包含的子class的模型class,我在这里只举例说明一个:
public class LoginCredentialsConfiguration
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string TenantId { get; set; }
}
- 在您的 Program.cs class 中,您现在可以像这样从 appsettings.json 中获取参数:
var aH = new AppSettingsHandler("appsettings.json");
var aS = aH.GetAppSettings();
var myPath = aS.DataBase.PathToDatabases;
当然,您可以调整该代码,使其符合您的要求,即。即,您必须定义自己的 classes 和 subclasses,当然您也可以通过获取 appsettings.json 的其他部分来扩展 AppSettingsHandler.cs。
很有帮助!
- appsettings.json(添加appsettings.json后,转到属性并将文件标记为复制到out目录)
{ "ConnectionString": "Server=localhost;Database=tempDB;Uid=<dbUserName>;Pwd=<dbPassword>", "Smtp": { "Host": "smtp.gmail.com", "Port": "587", "Username": "<YourGmailUserName>", "Password": "<YourGmailPassword>", "From": "Your Name" } }
2.package 需要
dotnet add package Microsoft.Extensions.Configuration dotnet add package Microsoft.Extensions.Configuration.Json
- program.cs
using System; using Microsoft.Extensions.Configuration; class Program { static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json", true, true); var config = builder.Build(); var connectionString = config["ConnectionString"]; var emailHost = config["Smtp:Host"]; Console.WriteLine($"Connection String is: {connectionString}"); Console.WriteLine($"Email Host is: {emailHost}"); Console.ReadLine(); } }
开始使用 Visual Studio 2022 和 .net 6。
- 创建一个新的控制台项目。
- 向项目添加一个 appsettings.json 文件。
- 右键单击 select 属性并确保将其复制到输出目录。
将文件编辑成如下所示。
{ "ConnectionString": "Server=localhost;Database=tempDB;Uid=<dbUserName>;Pwd=<dbPassword>", "Smtp": { "Host": "smtp.gmail.com", "From": "Your Name" }, "MySecondClass": { "SettingOne": "some string value", "SettingTwo": 82 } }
编辑您的项目 csproj 文件以包含 Microsoft.Extensions.Configuration and its json counter part 包。见下文,同时注意 appsettings.json 文件。
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.json" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
最后,您的 program.cs 文件将如下所示。
using System; using System.IO; using Microsoft.Extensions.Configuration; // See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, World!"); var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json", true, true); var config = builder.Build(); var connectionString = config["ConnectionString"]; var emailHost = config["Smtp:Host"]; Console.WriteLine($"Connection String is: {connectionString}"); Console.WriteLine($"Email Host is: {emailHost}"); var settingTwo = config["MySecondClass:SettingOne"]; Console.WriteLine(settingTwo);
我试过以下方法,效果很好。
1- 将您的 launchSettings.json 添加到 Properties 文件夹下的项目.
2- 将 appsettings 文件添加到每个环境的项目中。
3- 将 appsettings 文件添加到 .csproj 中,如下所示。
4-然后你可以通过下面的代码根据环境注入并到达读取appsettings文件的IConfiguration。
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.{environment}.json")
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
var serviceProvider = new ServiceCollection()
.AddSingleton<IConfiguration>(configuration)
.BuildServiceProvider();
var configurationInstance = serviceProvider.GetService<IConfiguration>();
launchSettings.json
{
"profiles": {
"YourProject": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "DEV"
}
}
}
}
您应该在 .csproj 文件中添加您的 appSettings 文件
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="6.3.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.DEV.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.Production.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.QA.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
你可以在任何地方注入它
public class ConnectionService
{
private readonly IConfiguration _configuration;
public ConnectionService(IConfiguration configuration)
{
_configuration = configuration;
}
}
我正在使用 dotnet 6。 您只需要在主机上调用 CreateDefaultBuilder。
await Host
.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services
.AddHostedService<ConsoleHostedService>();
})
.RunConsoleAsync();
其中 ConsoleHostedService 实现 IHostedService。
通过调用 ConfigureServices 它会做你需要的。