.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. java列队使用案例

    java队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作. 具有先进先出的特性 LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Que ...

  2. Spring不能直接@autowired注入Static变量

    一.业务场景 spring框架应用中有些静态方法需要依赖被容器管理的类,就像这样: @Component public class Test { @Autowired private static U ...

  3. 深度学习剖根问底: Adam优化算法的由来

    在调整模型更新权重和偏差参数的方式时,你是否考虑过哪种优化算法能使模型产生更好且更快的效果?应该用梯度下降,随机梯度下降,还是Adam方法? 这篇文章介绍了不同优化算法之间的主要区别,以及如何选择最佳 ...

  4. 手动计算UTXO

    const TX_TYPE_IN = 1; const TX_TYPE_OUT = 2; export const CreateUtxos = async (address: string, data ...

  5. Hash算法及java HashMap底层实现原理理解(含jdk 1.7以及jdk 1.8)

    现在很多公司面试都喜欢问java的HashMap原理,特在此整理相关原理及实现,主要还是因为很多开发集合框架都不甚理解,更不要说各种其他数据结构了,所以造成面子造飞机,进去拧螺丝. 1.哈希表结构的优 ...

  6. Java: 线程池(ThreadPoolExecutor)中的参数说明

    最近在看<阿里巴巴Android开发手册>,里面有这样几句话: [强制]新建线程时,必须通过线程池提供(AsyncTask 或者ThreadPoolExecutor或者其他形式自定义的线程 ...

  7. Oracle 日期各个部分常用写法

    --1.日期的各部分的常用的的写法 --- --1) 取时间点的年份的写法: SELECT TO_CHAR(SYSDATE,'YYYY') FROM DUAL; --结果:2019 --2) 取时间点 ...

  8. Python + Selenium 自动发布文章(一):开源中国

    https://blog.csdn.net/qq_28804275/article/details/80891949 https://blog.csdn.net/qq_28804275/article ...

  9. somatic mutation体细胞变异检测文献分享--转载

    转载 :http://blog.sina.com.cn/s/blog_83f77c940102xuro.html Kalatskaya I, Trinh Q M, Spears M, et al. I ...

  10. 查看ssh有没有被黑的IP

    #grep "Failed password " /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr ...