You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core 6的Program.cs中读取appsettings.json配置

问题背景

我在appsettings.json中定义了Project配置节,包含ConnectionString、CompanyName等配置项;同时在MyCompany.Service命名空间下创建了带静态属性的Config类。在Visual Studio 2019中,通过Startup类的Configuration.Bind方法能实现配置绑定,页面可直接用@Config.CompanyEmail调用配置值。但在ASP.NET Core 6的Program.cs中,不清楚该如何配置以实现同样效果。

相关代码如下:

appsettings.json 配置

{
  "Project": {
    "ConnectionString": "Data Source=(local)\\SQLSERVER; Database=MyCompany; Persist Security Info=false; User ID='sa'; Password='sa'; MultipleActiveResultSets=True; Trusted_Connection=False;",
    "CompanyName": "My company",
    "CompanyPhone": "+1 (111) 111-11-11",
    "CompanyPhoneShort": "+11111111111",
    "CompanyEmail": "contact@mycompany.com"
  }
}

Config 类代码

namespace MyCompany.Service
{
  public static class Config // 建议改为静态类,更符合静态属性的使用场景
  {
    public static string ConnectionString { get; set; }
    public static string CompanyName { get; set; }
    public static string CompanyPhone { get; set; }
    public static string CompanyPhoneShort { get; set; }
    public static string CompanyEmail { get; set; }
  }
}

旧版(Visual Studio 2019)Startup 类工作代码

namespace MyCompany
{
  public class Startup
  {
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration) => Configuration = configuration;
    
    public void ConfigureServices(IServiceCollection services)
    {
      Configuration.Bind("Project", new Config());
      // 其他服务配置...
    }
  }
}
解决方法

在ASP.NET Core 6的Program.cs中,直接获取Project配置节并绑定到静态Config类即可,步骤如下:

  1. 引用命名空间:在Program.cs顶部添加Config类所在的命名空间引用;
  2. 绑定配置:通过配置节的Bind方法,直接绑定到Config静态类上(无需实例化)。

完整Program.cs示例代码:

using MyCompany.Service; // 必须添加该命名空间引用

var builder = WebApplication.CreateBuilder(args);

// 添加基础服务
builder.Services.AddControllers();
builder.Services.AddRazorPages();

// 绑定Project配置节到Config静态类
builder.Configuration.GetSection("Project").Bind(typeof(Config));

var app = builder.Build();

// 配置HTTP请求管道
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();

app.Run();

关键说明

  • 使用Bind(typeof(Config))而非Bind(new Config()):因为Config是静态类,无需实例化,直接绑定到其静态属性即可;
  • 绑定完成后,可在Razor页面中继续使用@Config.CompanyEmail的方式直接访问配置值;
  • 该方式会在应用启动时一次性加载配置,适合无需动态刷新配置的场景。

内容的提问来源于stack exchange,提问作者MityaYarkov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:57:05