如何在.Net 6控制台应用程序中读取appsettings.json?

jw5wzhpr  于 2022-11-19  发布在  .NET
关注(0)|答案(7)|浏览(316)

我尝试创建一个.Net 6控制台应用程序,但阅读appsettings.json文件时遇到问题。在Web应用程序中,我可以使用此...

var builder = WebApplication.CreateBuilder(args);

但是在控制台应用程序中我应该使用什么呢?当我试图将它添加到program.cs时,我得到了这个错误。"The name 'WebApplication' does not exist in the current context"

9avjhtql

9avjhtql1#

在应用程序中添加这两个nuget包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
然后,您可以使用ConfigurationBuilder来使用appsettings.json文件

var configuration =  new ConfigurationBuilder()
     .AddJsonFile($"appsettings.json");
            
var config = configuration.Build();
var connectionString = config.GetConnectionString("ConnectionString");

Getting Values from AppSettings in Console Application
Adding AppSettings in .net core app

kpbpu008

kpbpu0082#

链接到文档:https://learn.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" />

使用微软.扩展.配置;

// 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!;
}
e5njpo68

e5njpo683#

使用.NET 6控制台应用程序,请尝试:

using IHost host = Host.CreateDefaultBuilder(args).Build();

IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

string con= config.GetValue<string>("ConnectionStrings:conn1");
//OR
string connectionString = config["ConnectionStrings:conn1"];

Console.WriteLine($"Hello, World! {connectionString}");

json(属性):(复制到输出目录=始终):

"ConnectionStrings": {
    "conn1": "Server=localhost;Database=MyDatabase;Trusted_Connection=True", 
  }
ilmyapht

ilmyapht4#

在一个控制台应用程序中,我添加了appsettings.jsonuser 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();

        ...
    }
}

然后,在控制台应用程序的其他地方,在任何类中,您都可以简单地这样调用它

var someSetting = Program.Configuration["SomeSetting"];

如果你想要一个强类型的类,那么请看SO上的答案.net core Console application strongly typed Configuration

wgx48brx

wgx48brx5#

您可以使用DI来获取IConfiguration接口,并使用它来访问appsettings。

gupuwyp2

gupuwyp26#

安装以下软件包

Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Hosting

创建一个名为appsettings.json文件

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "defaultConnection": "data source=.;initial catalog=ExchangeGatewayDb;integrated security=true;MultipleActiveResultSets=True;"
  }
}

将此代码添加到Programe.cs

var hostBuilder = new HostBuilder().ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        }).ConfigureAppConfiguration((context, builder) =>
        {
            var env = context.HostingEnvironment;
            builder.SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();

            var configuration = builder.Build();
            var connectionString = configuration["ConnectionStrings:defaultConnection"];
        }).ConfigureServices(services =>
        {
            services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
            //your code
        });

var buildHost = hostBuilder.Build();
buildHost.Run();
wmomyfyw

wmomyfyw7#

我更喜欢下面的代码,因为它会自动从项目目录中读取appsettings.json文件。请注意我在配置DbContext时使用的_.Configuration来读取连接字符串。

var builder = Host.CreateDefaultBuilder(args)
        .ConfigureServices(
                (_, services) => services
                    .AddTransient<IService, Service>()
                    .AddDbContext<ApplicationDbContext>(options =>
                        options.UseNpgsql(
                      _.Configuration.GetConnectionString("DefaultConnection"),
                            b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)))
                    );
var host = builder.Build();

var dbContext = host.Services.GetRequiredService<ApplicationDbContext>();

我把这些联系起来:https://bjdejongblog.nl/net-core-6-dependency-injection-console-program/

相关问题