如何在 .Net 6 控制台应用程序中读取 appsettings.json?
How can I read the appsettings.json in a .Net 6 console application?
我尝试创建 .Net 6 控制台应用程序,但无法读取我的 appsettings.json 文件。在 Web 应用程序中,我可以使用这个...
var builder = WebApplication.CreateBuilder(args);
但是我会在控制台应用程序中使用什么?尝试将其添加到 program.cs 时出现此错误。 "The name 'WebApplication' does not exist in the current context"
您可以使用 DI 获取 IConfiguration 界面,并通过它访问应用程序设置。
在控制台应用程序中,我像这样添加 appsettings.json
和 user secrets
,您也可能有一个开发 json 文件。
internal class Program
{
internal static IConfigurationRoot Configuration;
public static void Main()
=> new Program().MainAsync().GetAwaiter().GetResult();
private async Task MainAsync()
{
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configurationBuilder.AddUserSecrets(typeof(Program).GetTypeInfo().Assembly, optional: false);
Configuration = configurationBuilder.Build();
...
}
}
然后在控制台应用程序的任何其他地方 class 你可以像这样简单地调用它
var someSetting = Program.Configuration["SomeSetting"];
如果你想要一个强类型 class 然后在 SO
上看到这个答案
在您的应用程序中添加这两个 nuget 包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
然后就可以使用ConfigurationBuilder来使用appsettings.json文件
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json");
var config = configuration.Build();
var connectionString = config["ConnectionString"];
Link 到文档:https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration
执行此操作所需的 Nuget 包:
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" />
使用 Microsoft.Extensions.Configuration;
// Build a config object, using env vars and JSON providers.
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
// Get values from the config given their key and their target type.
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();
// Write the values to the console.
Console.WriteLine($"KeyOne = {settings.KeyOne}");
Console.WriteLine($"KeyTwo = {settings.KeyTwo}");
Console.WriteLine($"KeyThree:Message = {settings.KeyThree.Message}");
// Application code which might rely on the config could start here.
// This will output the following:
// KeyOne = 1
// KeyTwo = True
// KeyThree:Message = Oh, that's nice...
JSON 文件 (appsettings.json)
{
"Settings": {
"KeyOne": 1,
"KeyTwo": true,
"KeyThree": {
"Message": "Oh, that's nice..."
}
}
}
UPD:我检查了方法及其工作;
我的代码:
// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
Console.WriteLine("Hello, World!");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfiguration c = configurationBuilder.AddJsonFile("appsettings.json").AddEnvironmentVariables().Build();
var k = c.GetRequiredSection("Settings").Get<Settings>().KeyOne;
var n = 1;
public class NestedSettings
{
public string Message { get; set; } = null!;
}
public class Settings
{
public int KeyOne { get; set; }
public bool KeyTwo { get; set; }
public NestedSettings KeyThree { get; set; } = null!;
}
我尝试创建 .Net 6 控制台应用程序,但无法读取我的 appsettings.json 文件。在 Web 应用程序中,我可以使用这个...
var builder = WebApplication.CreateBuilder(args);
但是我会在控制台应用程序中使用什么?尝试将其添加到 program.cs 时出现此错误。 "The name 'WebApplication' does not exist in the current context"
您可以使用 DI 获取 IConfiguration 界面,并通过它访问应用程序设置。
在控制台应用程序中,我像这样添加 appsettings.json
和 user secrets
,您也可能有一个开发 json 文件。
internal class Program
{
internal static IConfigurationRoot Configuration;
public static void Main()
=> new Program().MainAsync().GetAwaiter().GetResult();
private async Task MainAsync()
{
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configurationBuilder.AddUserSecrets(typeof(Program).GetTypeInfo().Assembly, optional: false);
Configuration = configurationBuilder.Build();
...
}
}
然后在控制台应用程序的任何其他地方 class 你可以像这样简单地调用它
var someSetting = Program.Configuration["SomeSetting"];
如果你想要一个强类型 class 然后在 SO
上看到这个答案在您的应用程序中添加这两个 nuget 包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
然后就可以使用ConfigurationBuilder来使用appsettings.json文件
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json");
var config = configuration.Build();
var connectionString = config["ConnectionString"];
Link 到文档:https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration
执行此操作所需的 Nuget 包:
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" />
使用 Microsoft.Extensions.Configuration;
// Build a config object, using env vars and JSON providers.
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
// Get values from the config given their key and their target type.
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();
// Write the values to the console.
Console.WriteLine($"KeyOne = {settings.KeyOne}");
Console.WriteLine($"KeyTwo = {settings.KeyTwo}");
Console.WriteLine($"KeyThree:Message = {settings.KeyThree.Message}");
// Application code which might rely on the config could start here.
// This will output the following:
// KeyOne = 1
// KeyTwo = True
// KeyThree:Message = Oh, that's nice...
JSON 文件 (appsettings.json)
{
"Settings": {
"KeyOne": 1,
"KeyTwo": true,
"KeyThree": {
"Message": "Oh, that's nice..."
}
}
}
UPD:我检查了方法及其工作; 我的代码:
// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
Console.WriteLine("Hello, World!");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfiguration c = configurationBuilder.AddJsonFile("appsettings.json").AddEnvironmentVariables().Build();
var k = c.GetRequiredSection("Settings").Get<Settings>().KeyOne;
var n = 1;
public class NestedSettings
{
public string Message { get; set; } = null!;
}
public class Settings
{
public int KeyOne { get; set; }
public bool KeyTwo { get; set; }
public NestedSettings KeyThree { get; set; } = null!;
}