ASP.NET Core 读取 JSON 格式配置文件的流程:
-
在
appsettings.json
文件中定义所需的配置项。 -
在
Program.cs
文件中使用CreateDefaultBuilder(args)
方法创建IHostBuilder
对象,并在ConfigureAppConfiguration(...)
方法中添加读取配置文件的功能。 -
在需要使用配置项的组件中注入
IConfiguration
对象,并使用GetSection(...)
方法获取对应节点下的配置项。
下面是一个完整的示例:
Step 1:定义配置项和设置文件路径
在 appsettings.json
文件中定义需要的配置项,如下所示:
{
"AppSettings": {
"Title": "My Website",
"Version": "1.0.0",
"Database": {
"Type": "SqlServer",
"ConnectionString": "Server=(local);Database=mydb;Trusted_Connection=True;"
}
}
}
在 Program.cs
文件中设置配置文件路径,如下所示:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory()); // 设置配置文件路径
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); // 添加配置文件
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Step 2:在Startup.cs中获取配置项
在 Startup.cs
文件中通过构造函数注入 IConfiguration
对象,并使用 GetSection(...)
方法来获取指定配置项。
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// 获取配置项
string title = _configuration.GetSection("AppSettings:Title").Value;
string version = _configuration.GetSection("AppSettings:Version").Value;
string dbType = _configuration.GetSection("AppSettings:Database:Type").Value;
string connectionString = _configuration.GetSection("AppSettings:Database:ConnectionString").Value;
// 将配置项注册到依赖注入容器中
services.AddSingleton(new AppSettings(title, version, new DatabaseSettings(dbType, connectionString)));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
}
}
示例一:在控制器中获取配置项
[Route("api/[controller]")]
[ApiController]
public class ConfigController : ControllerBase
{
private readonly AppSettings _appSettings;
public ConfigController(AppSettings appSettings)
{
_appSettings = appSettings;
}
[HttpGet]
public IActionResult GetConfig()
{
return Ok(new
{
Title = _appSettings.Title,
Version = _appSettings.Version,
Database = _appSettings.Database
});
}
}
示例二:在中间件中获取配置项
public class CustomMiddleware
{
private readonly RequestDelegate _next;
private readonly AppSettings _appSettings;
public CustomMiddleware(RequestDelegate next, AppSettings appSettings)
{
_next = next;
_appSettings = appSettings;
}
public async Task Invoke(HttpContext httpContext)
{
// 使用配置项
string title = _appSettings.Title;
string version = _appSettings.Version;
string dbType = _appSettings.Database.Type;
string connectionString = _appSettings.Database.ConnectionString;
await _next(httpContext);
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:ASP.NET CORE读取json格式配置文件 - Python技术站