.net core 设置读取JSON配置文件 appsettings.json

Startup.cs 中

    public class Startup
{
public Startup(IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) //增加环境配置文件,新建项目默认有
.AddEnvironmentVariables()
.Build();
}
public IConfiguration Configuration { get; }
....

类库中

            var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Test.json", true, reloadOnChange: true); var config = builder.Build(); //读取配置
var a = config["JWTSettings:Secret"];

使用.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)这种方法可以保证可以修改正在运行的dotnet core 程序,不需要重启程序

使用Newtonsoft.Json 查询/修改,以及修改 appsettings.json 文件

ReadObject

        public IActionResult ReadObject()
{
string json = @"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabyte hard drive'
]
}"; JsonTextReader reader = new JsonTextReader(new StringReader(json));
var string1 = "";
while (reader.Read())
{
if (reader.Value != null)
{
string1 += "reader.Value != null: Token: " + reader.TokenType + ", Value: " + reader.Value + " <br/>";
}
else
{
string1 += "reader.Value == null: Token: " + reader.TokenType + " <br/>";
}
} ViewData["string"] = string1;
return View();
}

ReadJSON 读取Json 文件

Newtonsoft.Json

使用Newtonsoft.Json效果如截图

    public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
} public IActionResult ReadJSON()
{
string contentPath = _hostingEnvironment.ContentRootPath + @"\"; ; //项目根目录
var filePath = contentPath + "appsettings.json";
using (StreamReader file = new StreamReader(filePath))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader); string LicenceKey = (string)o2["appSettings"]["Key"]; ViewData["string"] = LicenceKey;
return View();
}
}

Microsoft.Extensions.Configuration

使用Microsoft.Extensions.Configuration

        public IActionResult Index()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Test.json", true, reloadOnChange: true); var config = builder.Build(); //读取配置
ViewData["Secret"] = config["appSettings:Key"];
return View();
}

修改 appsettings.json后的效果

  • Newtonsoft.Json

  • Microsoft.Extensions.Configuration

修改 appsettings.json

StreamWriter直接覆盖

    public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public IActionResult WriteJSON()
{
string contentPath = _hostingEnvironment.ContentRootPath + @"\"; ; //项目根目录
var filePath = contentPath + "appsettings.json";
JObject jsonObject;
using (StreamReader file = new StreamReader(filePath))
using (JsonTextReader reader = new JsonTextReader(file))
{
jsonObject = (JObject)JToken.ReadFrom(reader);
jsonObject["appSettings"]["Key"] = "asdasdasdasd";
} using (var writer = new StreamWriter(filePath))
using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
{
jsonObject.WriteTo(jsonwriter);
} return View();
}

效果如图



缺点 格式化的json和注释都没了

最新文章

  1. python之局部变量引用赋值前的结果
  2. Writing Text Files On The Client in Oracle Forms 10g
  3. c/c++内存调试
  4. UIPickerView自定义背景
  5. C# 访问控制:public、private、protected和internal
  6. javascript基础知识--什么是构造函数?什么是实例化对象?
  7. A9逻辑编译问题
  8. CSS3动画变形Animations
  9. MySQL 5.7.10 免安装配置
  10. Sublime Text2
  11. (Problem 37)Truncatable primes
  12. D3.js:力导向图
  13. 每天一道Java题[3]
  14. Golang &#27491;&#21017;&#34920;&#36798;&#24335;Regex&#30456;&#20851;&#36164;&#26009;&#25972;&#29702;
  15. 慢腾腾的Quartus prime16.0加快编译速度
  16. label与input之间的对应
  17. css3实现好看的边框效果
  18. 18-09-20 关于Excel 表格重复问题解决示例
  19. 学习笔记之Gurobi
  20. 火兰hillstone与fortigate之ipsec v.p.n连接实践

热门文章

  1. [后渗透]获取到 Meterpreter 之后的操作
  2. 查看Linux机器的外网IP
  3. Android Studio 之 数据存活【2】,返回桌面切换回来,内容还保存着
  4. mysql(一)工作原理 &amp; 数据库引擎
  5. OpenStack创建网络和虚拟机、dhcp设备、虚拟路由器、虚拟机访问外网原理分析
  6. 【转】Linux下的CPU使用率与服务器负载的关系与区别
  7. maven 工具
  8. python lambda表达式简单用法【转】
  9. [python]pypy优化python性能
  10. C#实体类对应SQL数据库的自增长ID怎么设置?