Thêm một tập tin json
đến gốc của dự án của bạn dir: config.json
{
"AppSettings": {
"TestKey" : "TestValue"
}
}
Tạo một class
mới cho cấu hình deserialization:
public class AppSettings
{
public string TestKey { get; set; }
}
Trong Startup.cs
:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvc();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
Nhận các tùy chọn trong controller
của bạn:
public HomeController(IOptions<AppSettings> settings)
{
var value = settings.Value.TestKey;
}
Nguồn
2015-12-14 17:49:22
Trong phần 'Tham khảo', tôi đã thêm' System.Configuration (1.0.0) 'đến DNX 4.5.1. Tuy nhiên, tôi vẫn nhận được "Loại hoặc không gian tên 'Cấu hình' không tồn tại trong không gian tên 'Hệ thống' (bạn đang thiếu một hội đồng hoặc tham chiếu?)" –