.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和注释都没了

.net core 读取、修改配置文件appsettings.json的更多相关文章

  1. IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题

    IT咨询顾问:一次吐血的项目救火   年后的一个合作公司上线了一个子业务系统,对接公司内部的单点系统.我收到该公司的技术咨询:项目启动后没有规律的突然无法登录了,重新启动后,登录一断时间后又无法重新登 ...

  2. asp.net core mvc 读取配置文件appsettings.json

    上一篇我们将了读取自定义配置文件.这篇我们讲一下asp.net core mvc里读取自带的配置文件 appsettings.json 首先创建个asp.net core mvc项目,项目里有Prog ...

  3. 循序渐进学.Net Core Web Api开发系列【6】:配置文件appsettings.json

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.本篇概述 本篇描 ...

  4. 每天记录一点:NetCore获得配置文件 appsettings.json vue-router页面传值及接收值 详解webpack + vue + node 打造单页面(入门篇) 30分钟手把手教你学webpack实战 vue.js+webpack模块管理及组件开发

    每天记录一点:NetCore获得配置文件 appsettings.json   用NetCore做项目如果用EF  ORM在网上有很多的配置连接字符串,读取以及使用方法 由于很多朋友用的其他ORM如S ...

  5. .NET Core在类库中读取配置文件appsettings.json

    在.NET Framework框架时代我们的应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别 ...

  6. .Net Core 读取配置文件 appsettings.json

    1. 首先些一个类 public class MySettings { public string P1 { get; set; } public string P2 { get; set; } } ...

  7. ASP.NET Core 类库中取读配置文件 appsettings.json

    首先引用NuGet包 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Json Microsoft.Exte ...

  8. 读取配置文件,appsettings.json和注入ICO

    https://www.cnblogs.com/knowledgesea/p/7079880.html 引入Nuget的两个类库 Microsoft.Extensions.Configuration ...

  9. .NET Core 获取配置文件appsettings.json 方法

    using Abp.Extensions; using Microsoft.Extensions.Configuration; using System; using System.Collectio ...

随机推荐

  1. sentinel-dashboard安装、运行(docker)

    https://github.com/alibaba/Sentinel/releases 下载源码 修改成支持nacos(略) mkdir /opt/sentinel-dashboard把编译好的se ...

  2. Linux下安装和使用MySQL数据库

    因为这个工具需要用到MySQL,https://github.com/ENCODE-DCC/caper,不得不再Linux服务器上安装. 首先服务器本身是有MySQL的, $ /usr/bin/mys ...

  3. [oracle/java/sql]用于上十万批量数据插入Oracle表的Java程序

    程序下载:https://files.cnblogs.com/files/xiandedanteng/LeftInnerNotExist20191222.rar 原理:Oracle的Insert al ...

  4. Redis 键的过期删除策略及缓存淘汰策略

    前言 Redis缓存淘汰策略与Redis键的过期删除策略并不完全相同,前者是在Redis内存使用超过一定值的时候(一般这个值可以配置)使用的淘汰策略:而后者是通过定期删除+惰性删除两者结合的方式进行内 ...

  5. linux删除文件的前n行

    需求描述: 今天看了一个系统的临时文件,有5.6G的大小,这个文件也没有用了,想要将大部分的文件都删除掉. 在此记录下删除的过程.删除前n行的记录. 操作过程: 对于数据量比较大的情况(本例5800万 ...

  6. vue中axios使用一:axios做拦截器

    转载请注明出处: 项目中用到了单点登录,依赖的公司通用的jar包,且项目为前后端分离的方式,为了管理系统的所有请求和 超时管理,用到了axios,做前端请求拦截,并做管理. 其有以下特点: axios ...

  7. Linux内核链表——看这一篇文章就够了

    本文从最基本的内核链表出发,引出初始化INIT_LIST_HEAD函数,然后介绍list_add,通过改变链表位置的问题引出list_for_each函数,然后为了获取容器结构地址,引出offseto ...

  8. 使用bugly热更新时自定义升级弹窗的UI样式

    项目的热更新用的bugly,不过一直都只是使用他自带的升级弹窗. 不过UI小姐姐说弹窗太丑了,要自定义. bugly有提供自定义UI的官方文档:https://bugly.qq.com/docs/us ...

  9. RabbitMQ的应用总结

    RabbitMQ是一个由erlang开发的AMQP(Advanced Message Queue )的开源实现.AMQP 的出现其实也是应了广大人民群众的需求,虽然在同步消息通讯的世界里有很多公开标准 ...

  10. ubuntu 各压缩文件解压命令大全

    .tar 解包:tar xvf xxx.tar 打包:tar cvf xxx.tar DirName (注:tar是打包,不是压缩!) .gz 解压1:gunzip FileName.gz 解压2:g ...