如何在Asp.net core 6的Program.cs文件中使用appsettings.json

157

我试图在我的Asp.net core v6应用程序的Program.cs文件中访问appsettings.json,但在这个版本的.Net中,Startup类和Program类合并在一起,并且using和其他语句都被简化并从Program.cs中删除。在这种情况下,如何访问IConfiguration或例如如何使用依赖注入?

代码

这是Asp.net 6为我创建的默认Program.cs:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

例如,我想在这行代码中使用 appsettings.json 而不是硬编码的 connectionstring :
options.Configuration = "localhost:6379";

该文件已经默认加载。真正的问题是如何访问“配置”? - Panagiotis Kanavos
3
在 .net 6 版本中,没有 Startup.cs 文件和 Program.cs 文件,它们被合并在了一个名为 Program.cs 的文件中。在这种新情况下,默认情况下不会创建 Configuration,并且我们无法将其注入。 - Sajed
1
这个回答是否解决了你的问题?如何在 .Net 6 控制台应用程序中读取 appsettings.json 文件? - Michael Freidgeim
15个回答

138

假设我们在appsettings中设置了

"settings": {
    "url": "myurl",
    "username": "guest",
    "password": "guest"
  }

我们有这个类

public class Settings
    {
        public string Url { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }

我们也可以使用

var settings = builder.Configuration.GetSection("Settings").Get<Settings>();

var url = settings.Url;

etc....


18
这应该被标记为适用于仅具有最小 startup.cs 类的 .NET Core 6 的正确答案。非常感谢您的示例! - Gerardo Verrone
1
我同意这是答案。我特意登录StackOverflow投票支持这个答案! - ProgBlogger
区分大小写吗? - Berkay
区分大小写吗? - undefined
不区分大小写。https://github.com/dotnet/runtime/blob/00ee1c18715723e62484c9bc8a14f517455fc3b3/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationProvider.cs#L24 - GGleGrand
我使用桌面Windows Forms应用程序或控制台应用程序。如何使用它? - Kiquenet

95

虽然上面的例子是有效的,但实现这个功能的正确方式如下:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration["Redis"];
});

WebApplicationBuilder 有一个配置对象作为其属性,您可以使用它。


假设在开发环境的 JSON 文件中,我创建了一个名为 key1 的键,在生产环境的 JSON 文件中,我创建了一个名为 key2 的键。然而,当我在 Visual Studio 中运行项目时,它读取了这两个键。难道它不应该只读取开发环境 JSON 文件中的键吗? - variable
你具体在问什么? - davidfowl
使用带有program.cs的控制台应用程序。我无论如何都无法让它工作。我尝试添加命名空间NuGet包,但似乎没有任何东西能够识别WebApplication。var builder = WebApplication.CreateBuilder(args); - AndyMan
2
使用空的 Web 项目。如果您想在控制台应用程序中访问 ASP.NET API,则需要向 Microsoft.AspNetCore.App 添加 FrameworkReference。 - davidfowl

38

默认情况下会包含appsettings.json文件,您可以直接使用它。如果您想显式地包含文件,可以像这样包含它们:

builder.Configuration.AddJsonFile("errorcodes.json", false, true);

像这样的依赖注入

builder.Services.AddDbContext<>() // like you would in older .net core projects.

在.NET 6中,这不起作用。AddDbContext不存在。是否缺少using? - dvallejo
1
我同意在 NET 6 中无法工作。AddJsonFile 方法不是 ConfigurationBuilder 类的一部分。 - Oliver Nilsen
1
@OliverNilsen 当然可以。你可以通过以下代码进行测试:'var config = new ConfigurationBuilder().AddJsonFile("x.json").Build();',同时也可以像Mayur Ekbote提到的那样使用builder.Configuration.AddJsonFile(...)来实现相同的功能。 - Bandook
3
它起作用了,但我需要先手动添加 NuGet 包在 .NET Core 6 中。 <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> - Oliver Nilsen
你只需要使用这个包:Microsoft.Extensions.Configuration.Json。如果你想要使用AddJsonFile的话。 - N-ate
我会将此标记为已接受的答案。 - Vish

31
假设一个名为appsettings.json的文件。
{
    "RedisCacheOptions" : {
        "Configuration": "localhost:6379"
    }
}

您可以构建一个配置对象来提取所需的设置,没有任何阻止。

IConfiguration configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = configuration["RedisCacheOptions:Configuration"];
});

//...

是的,这是一种很好的构建方式,在旧版本中,我们是通过注入配置来构建它,而不是在Startup.cs中构建。 - Sajed
什么是“WebApplication”? 项目名称? - Fandango68
@Fandango68 请查看此处的文档 https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.builder.webapplication - Nkosi
实际上,我发现这个解决方案是针对 Web 应用程序的。我的是控制台应用程序。我的解决方案在这里:https://dev59.com/NVEG5IYBdhLWcg3wKFXw - Fandango68

27

通过注入方式检索appsettings.json部分的值

appsettings.json 部分:

{
  "AppSettings": {
    "Key": "Value"
  }
}

AppSettings.cs:

public class AppSettings
{
    public string Key { get; set; }
}

Program.cs:

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

通过构造函数注入IOptions<>

private readonly AppSettings _appSettings;

public HomeController(
    IOptions<AppSettings> options)
{
    _appSettings = options.Value;
}

17
创建一个类:
public class RedisCacheOptions
{
    public string Configuration { get; set; }
}

然后,在您的program.cs文件中执行以下操作:

var redisCacheOptions = new RedisCacheOptions();
builder.Configuration.GetSection(nameof(RedisCacheOptions)).Bind(redisCacheOptions);

现在,您只需说出以下内容即可访问配置信息:

redisCacheOptions.Configuration

假设你在appSettings.json中有一个嵌套结构,就像这样:

"AuthenticationConfiguration": {
  "JwtBearerConfiguration": {
    "Authority": "https://securetoken.google.com/somevalue",
    "TokenValidationConfiguration": {
      "Issuer": "https://securetoken.google.com/somevalue",
      "Audience": "somevalue"
    }
  }
}

那么,你的类结构将会是这样的:

public class AuthenticationConfiguration
{
    public JwtBearerConfiguration JwtBearerConfiguration { get; set; } = new JwtBearerConfiguration();
}

public class JwtBearerConfiguration
{
    public string Authority { get; set; }

    public TokenValidationConfiguration TokenValidationConfiguration { get; set; } =
        new TokenValidationConfiguration();
}

public class TokenValidationConfiguration
{
    public string Issuer { get; set; }
    public string Audience { get; set; }
}

有了这个,如果你要做:

var authConf = new AuthenticationConfiguration();
builder.Configuration.GetSection(nameof(AuthenticationConfiguration)).Bind(authConf);

然后在您的程序中,您可以这样访问值:

AuthenticationConfiguration.JwtBearerConfiguration.Authority

采用这种方法可以避免使用魔法字符串,并获得智能提示,所以是双赢的。


3
谢谢你展示 builder.Configuration.GetSection()。这正是我在寻找的! - symbiont

8

因为我的应用程序是一个.NET Core 6控制台应用程序,所以我首先需要安装NuGet包:

  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.Configuration

然后添加它们的关联使用:

  • using Microsoft.Extensions.Hosting;
  • using Microsoft.Extensions.Configuration;

接下来,我将这段代码添加到Program.cs文件中。

// Build a config object, using env vars and JSON providers.
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();

我有一个Settings.cs类来接受我的appsettings.json文件中的值。

Settings.cs

internal class Settings
{
    public static string Setting1 { get; set; }
    public static string Setting2 { get; set; }
    public static string Setting3 { get; set; }

}

还有AppSettings.json文件

"Settings": {
    "Setting1": "yep",
    "Setting2": "nope",
    "Setting3": "kjkj"
  }

这篇来自微软的资源帮助我了解并掌握了新的.NET Core 6架构

https://learn.microsoft.com/zh-cn/dotnet/core/extensions/configuration


没有main()函数真的让我很困惑! - KirstieBallance

8
在Program.cs文件中,尝试使用以下代码:
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

ConfigurationManager configuration = builder.Configuration;

var rabbitMQSection = configuration.GetSection("RabbitMQ");
var rabbitMQConnectionUrl = rabbitMQSection["ConnectionUrl"];

appsettings.json 文件所在的位置:

"AllowedHosts": "*",
"RabbitMQ": {
    "ConnectionUrl": "amqp://guest:guest@localhost:5672/"
}

1
我本来想添加一个关于引用 builder.Configuration 的答案。好主意! - psiodrake

8

已解决:在dotnet6中的program.css文件中获取appsetting值

appsettings.json

  "AllowedHosts": "*",
  "ServiceUrls": {
  "EmployeeAPI": "https://localhost:44377/" },

Program.cs

var builder = WebApplication.CreateBuilder(args);    
var provider = builder.Services.BuildServiceProvider();
var configuration = provider.GetService<IConfiguration>();
SD.EmployeeAPIBase = configuration.GetValue<string>("ServiceUrls:EmployeeAPI");

类的静态变量:

public static class SD //Static Details
{
    public static string EmployeeAPIBase { get; set; }     
}

最后,使用完整的 URL。

URL = SD.EmployeeAPIBase + "api/EmpContact/GetGovernates"

我有类似的情况,但这些代码不起作用,在我的代码中,程序.cs中的值仍然为空。您能否提供完整的代码参考一下? - Vipin Jha

4

以下是如何在Program.cs文件中获取appsettings.json值的方法,这里提供一个示例:

appsettings.json 文件

  "Jwt": {
    "Key": "ThisismySecretKey",
    "Issuer": "www.joydipkanjilal.net"
  },

获取 Program.cs 文件中的值

var app = builder.Build();
var config = app.Configuration;
var key = config["Jwt:Key"];
var issuer = config["Jwt:Issuer"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接