1. 程式人生 > >.Net Core 讀取appsettings.json中的配置

.Net Core 讀取appsettings.json中的配置

在.net core中預設是沒有*.config 檔案的配置檔案都是*.json

一、NuGet包管理器引用或者在project.json寫入下面這些包

 "Microsoft.Extensions.Options.ConfigurationExtensions": "2.1.1",
 "Microsoft.Extensions.Configuration.Json": "2.1.1"

二、修改 appsettings.json

 {
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "MyOwn": {
    "Name": "wula",
    "Age": 12
  }
}

三、在Models資料夾中新建一個MyOwnModel類來對應配置資訊

public class MyOwnModel
{
    public string Name { get; set; }
    public string Age { get; set; }
}

四、配置Startup.cs

首先用AddOptions() 初始化注入IOptions<T>,然後Configure<MyOwnModel>則是自動初始化MyOwnModel例項並且對映appSettings裡的配置

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    //初始化MyOwnModel例項並且對映appSettings裡的配置
    services.AddOptions();
    services.Configure<MyOwnModel>(Configuration.GetSection("MyOwn"));
}

五、在Controller中使用

public class TestController : Controller
{
    private IOptions<MyOwnModel> settings;
    public TestController(IOptions<MyOwnModel> settings)
    {
        this.settings = settings;
    }
    public IActionResult Test()
    {
        ViewData["Name"] = this.settings.Value.Name;
        ViewData["Age"] = this.settings.Value.Age;
        return View();
    }
}