var configuration = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json");
var config = configuration.Build();
var connectionString = config.GetConnectionString("ConnectionString");
// 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...
// 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!;
}
7条答案
按热度按时间9avjhtql1#
在应用程序中添加这两个nuget包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
然后,您可以使用ConfigurationBuilder来使用appsettings.json文件
Getting Values from AppSettings in Console Application
Adding AppSettings in .net core app
kpbpu0082#
链接到文档:https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration
为此需要Nuget软件包:
使用微软.扩展.配置;
JSON文件(appsettings.json)
UPD:我检查了方法,它工作;我的代码:
e5njpo683#
使用.NET 6控制台应用程序,请尝试:
json(属性):(复制到输出目录=始终):
ilmyapht4#
在一个控制台应用程序中,我添加了
appsettings.json
和user secrets
,这样你也可以有一个开发json文件。然后,在控制台应用程序的其他地方,在任何类中,您都可以简单地这样调用它
如果你想要一个强类型的类,那么请看SO上的答案.net core Console application strongly typed Configuration
wgx48brx5#
您可以使用DI来获取IConfiguration接口,并使用它来访问appsettings。
gupuwyp26#
安装以下软件包
创建一个名为
appsettings.json
文件将此代码添加到
Programe.cs
wmomyfyw7#
我更喜欢下面的代码,因为它会自动从项目目录中读取appsettings.json文件。请注意我在配置DbContext时使用的
_.Configuration
来读取连接字符串。我把这些联系起来:https://bjdejongblog.nl/net-core-6-dependency-injection-console-program/