.NET Core 读取appsettings.json
Posted ♀影☆响
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET Core 读取appsettings.json相关的知识,希望对你有一定的参考价值。
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "AppSettings": { "SqlServerConnection": "Server=127.0.0.1;Database=demo;User ID=sa;Password=sa;", "RedisCaching": { "Enabled": true, "ConnectionString": "127.0.0.1:6379" } } }
1、初始化注入方式
Startup.cs下ConfigureServices方法:
services.AddOptions(); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
public class AppSettings { public RedisCaching RedisCaching { get; set; } } public class RedisCaching { /// <summary> /// 是否启用 /// </summary> public bool Enabled { get; set; } /// <summary> /// 链接信息 /// </summary> public string ConnectionString { get; set; } }
然后在控制器中调用:
public readonly IOptions<AppSettings> Setting; public HomeController(IOptions<AppSettings> setting) { Setting = setting; } public IActionResult Index() { var s = Setting.Value.RedisCaching.ConnectionString; ViewData["abc"] = s; return View(); }
2、读取appsettings.json方式
(此方法如在单独的类库中需引用Microsoft.Extensions.Options.ConfigurationExtensions、Microsoft.Extensions.Configuration.FileExtensions、Microsoft.Extensions.Configuration.Json)
1)先设置appsettings.json文件复制到根目录.右键appsettings.json 高级 复制到输出目录中选“始终复制”.
2)
public T Get<T>(string key) { IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, true).Build(); return config.GetSection(key).Get<T>(); }
public IActionResult Index() { var s = new GetAppSetting().Get<string>("AppSettings:SqlServerConnection"); ViewData["abc"] = s; return View(); }
第一种方法在别的类库中也可调用,比较方便,刚做core项目,用第一种方法时类库中不好调用,查了半天用第二种就可以了。
以上是关于.NET Core 读取appsettings.json的主要内容,如果未能解决你的问题,请参考以下文章
将 appsettings.json 文件中的机密存储在 Azure Key Vault 上的 .Net 控制台应用程序中