Đọc giá trị từ tệp cấu hình
Trong ứng dụng ASP.NET Core, tệp appsettings.json chứa các cấu hình cần thiết cho ứng dụng. Dưới đây là cách truy cập các giá trị này.
Ví dụ về cấu hình trong appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DatabaseConnection": "server=192.168.1.100;database=MyApp;uid=sa;pwd=pass123;MultipleActiveResultSets=true;"
}
}
Đọc chuỗi kết nối trong lớp Startup
Để đọc chuỗi kết nối DatabaseConnection trong lớp Startup, bạn có thể sử dụng một trong các cách sau:
public class Startup
{
// Tiêm dịch cấu hình
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
{
// Cách 1: Sử dụng phương thức GetConnectionString
// options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection"));
// Cách 2: Sử dụng GetSection để truy cập từng cấp
// options.UseSqlServer(Configuration.GetSection("ConnectionStrings").GetSection("DatabaseConnection").Value);
// Cách 3: Sử dụng ký tự phân cách
options.UseSqlServer(Configuration.GetSection("ConnectionStrings:DatabaseConnection").Value);
}, ServiceLifetime.Transient);
}
}
Sử dụng GetSection() để lấy giá trị phức tạp
Giả sử chúng ta có cấu hình phức tạp sau trong appsettings.json:
{
"AppSettings": {
"ApiPrefix": "/api/v1",
"Environment": "Production",
"Features": {
"Authentication": true,
"Caching": false,
"Logging": "Detailed"
}
}
}
Để lấy giá trị của phần Features, chúng ta cần thực hiện các bước sau:
1. Tạo các lớp tương ứng với cấu hình JSON
public class AppSettings
{
public string ApiPrefix { get; set; }
public string Environment { get; set; }
public Features Features { get; set; }
}
public class Features
{
public bool Authentication { get; set; }
public bool Caching { get; set; }
public string Logging { get; set; }
}
2. Đăng ký dịch vụ Options và tải cấu hình
public void ConfigureServices(IServiceCollection services)
{
// Chỉ yêu cầu với .NET Core 2.0
services.AddOptions();
// Đăng ký cấu hình AppSettings
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Hoặc đăng ký cấu hình con
services.Configure<Features>(Configuration.GetSection("AppSettings:Features"));
services.AddControllers();
}
3. Sử dụng trong Controller
[Route("api/[controller]")]
[ApiController]
public class ConfigController : ControllerBase
{
private readonly AppSettings _appSettings;
private readonly Features _features;
public ConfigController(
IOptions<AppSettings> appSettings,
IOptions<Features> features)
{
_appSettings = appSettings.Value;
_features = features.Value;
}
[HttpGet("app-settings")]
public ActionResult<AppSettings> GetAppSettings()
{
return _appSettings;
}
[HttpGet("features")]
public ActionResult<Features> GetFeatures()
{
return _features;
}
}
Lưu ý: Trước khi sử dụng, bạn phải đăng ký dịch vụ trong lớp Startup bằng cách sử dụng services.Configure. Nếu không làm bước này, dữ liệu sẽ không được đọc được.