在 ASP.NET Core 6 Program.cs 中使用 appsettings.json
问题概述
在 ASP.NET Core 6 中,Startup
类和 Program
类已经合并,传统的配置方式发生了变化。开发者需要了解如何在新模板中访问 appsettings.json
配置文件,以及如何使用依赖注入来获取配置值。
解决方案
基础配置访问方式
在 ASP.NET Core 6 中,WebApplication.CreateBuilder(args)
会自动加载 appsettings.json
文件,您可以直接通过 builder.Configuration
访问配置:
csharp
var builder = WebApplication.CreateBuilder(args);
// 直接访问配置值
var redisConfig = builder.Configuration["RedisCacheOptions:Configuration"];
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConfig;
});
配置强类型对象
为了更好的类型安全和 IntelliSense 支持,推荐使用强类型配置:
1. 创建配置类
csharp
public class RedisCacheOptions
{
public string Configuration { get; set; }
}
public class AppSettings
{
public RedisCacheOptions RedisCacheOptions { get; set; }
}
2. 在 Program.cs 中绑定配置
csharp
var builder = WebApplication.CreateBuilder(args);
// 方法1:直接绑定到对象
var redisOptions = new RedisCacheOptions();
builder.Configuration.GetSection("RedisCacheOptions").Bind(redisOptions);
// 方法2:使用依赖注入注册配置
builder.Services.Configure<RedisCacheOptions>(
builder.Configuration.GetSection("RedisCacheOptions"));
3. 在控制器中使用注入的配置
csharp
public class MyController : ControllerBase
{
private readonly RedisCacheOptions _redisOptions;
public MyController(IOptions<RedisCacheOptions> options)
{
_redisOptions = options.Value;
}
// 使用 _redisOptions.Configuration
}
连接字符串访问
对于连接字符串,可以使用专用方法:
csharp
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
环境特定配置
ASP.NET Core 自动根据环境加载不同的配置文件:
appsettings.json
- 通用配置appsettings.Development.json
- 开发环境配置appsettings.Production.json
- 生产环境配置
完整示例
appsettings.json
json
{
"RedisCacheOptions": {
"Configuration": "localhost:6379"
},
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=myDb;User Id=myUser;Password=myPassword;"
},
"Jwt": {
"Key": "YourSecretKey",
"Issuer": "YourIssuer",
"Audience": "YourAudience"
}
}
Program.cs 实现
csharp
var builder = WebApplication.CreateBuilder(args);
// 获取配置值
var redisConfig = builder.Configuration["RedisCacheOptions:Configuration"];
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
// 强类型配置绑定
builder.Services.Configure<RedisCacheOptions>(
builder.Configuration.GetSection("RedisCacheOptions"));
// 服务注册
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConfig;
});
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// 中间件配置
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();
最佳实践
TIP
- 使用强类型配置:避免魔术字符串,提高代码可维护性
- 环境特定配置:利用不同环境的配置文件
- 安全存储敏感数据:使用用户机密或环境变量存储密码等敏感信息
- 验证配置:使用选项模式验证配置值
WARNING
确保在 appsettings.json
中的配置键与代码中的访问路径完全匹配,包括大小写。
扩展配置
如果需要加载额外的配置文件:
csharp
builder.Configuration.AddJsonFile("customsettings.json", optional: true, reloadOnChange: true);
结论
在 ASP.NET Core 6 中,通过 builder.Configuration
可以轻松访问 appsettings.json
中的配置。推荐使用强类型配置和选项模式来提高代码的可维护性和类型安全性。这种方式既简洁又灵活,适合各种规模的应用程序开发。