答案:appsettings.json是.NET中用于存储配置的JSON文件,支持多环境配置和IConfiguration接口读取。通过环境变量ASPNETCORE_ENVIRONMENT加载对应appsettings.{Environment}.json文件,覆盖默认配置;可直接读取键值或使用强类型IOptions模式注入配置类,提升代码安全与可维护性。

.NET中的appsettings.json是应用程序的配置文件,用于存储键值对形式的设置信息,比如数据库连接字符串、日志级别、第三方服务密钥等。它采用JSON格式,结构清晰,易于维护。
appsettings.json 的基本结构
默认情况下,项目根目录下会包含一个appsettings.json文件,内容类似:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyApp;Trusted_Connection=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AppSettings": {
"SiteName": "My Website",
"PageSize": 10
}
}
你还可以为不同环境创建对应的配置文件,例如:
appsettings.Development.json
appsettings.Staging.json
appsettings.Production.json
这些文件会覆盖appsettings.json中相同路径的配置项。
如何读取配置
.NET内置了IConfiguration接口,可在依赖注入容器中直接使用。常见用法如下:
1. 在启动类中读取(如Program.cs或Startup.cs)
var builder = WebApplication.CreateBuilder(args);
// 配置文件已自动加载,无需手动添加
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var siteName = builder.Configuration["AppSettings:SiteName"];
2. 在控制器或服务中注入 IConfiguration
public class HomeController : Controller
{
private readonly IConfiguration _config;
public HomeController(IConfiguration config)
{
_config = config;
}
public IActionResult Index()
{
var siteName = _config["AppSettings:SiteName"];
var pageSize = _config.GetValue("AppSettings:PageSize");
return View();
}
}
3. 使用强类型配置(推荐方式)
// 定义配置类
public class AppSettings
{
public string SiteName { get; set; }
public int PageSize { get; set; }
}
// 在 Program.cs 中注册
builder.Services.Configure(builder.Configuration.GetSection("AppSettings"));
// 在服务中使用 IOptions
public class MyService
{
private readonly AppSettings _appSettings;
public MyService(IOptions options)
{
_appSettings = options.Value;
}
}
如何区分不同环境的配置
.NET通过环境变量ASPNETCORE_ENVIRONMENT决定加载哪个配置文件。常见值有:Development、Staging、Production。
环境配置加载规则:
-
appsettings.json:始终加载,作为基础配置
-
appsettings.{Environment}.json:根据当前环境加载,覆盖基础配置中的同名项
设置环境变量的方法:
-
开发环境:在
launchSettings.json中设置(位于Properties目录)
-
生产环境:通过操作系统环境变量或部署配置设置
// 示例:launchSettings.json 片段
"profiles": {
"Development": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Production": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
}
}
当环境为Development时,.NET会自动加载appsettings.Development.json并合并配置。
基本上就这些。配置系统灵活且强大,建议结合强类型选项模式使用,提升
代码可读性和安全性。