.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. Nagios HTTP WARNING: HTTP/1.1 403 Forbidden

    当我们第一次搭建好nagios后会有Nagios HTTP WARNING: HTTP/1.1 403 Forbidden告警 要解决这个问题, 可以创建一个html文件,然后重启两个服务,等待几分钟 ...

  2. 【Gamma阶段】第四次Scrum Meeting

    冰多多团队-Gamma阶段第四次Scrum会议 工作情况 团队成员 已完成任务 待完成任务 卓培锦 修改可移动button以及button手感反馈优化 编辑器风格切换(夜间模式) 牛雅哲 修复bug并 ...

  3. [Beta]Scrum Meeting#6

    github 本次会议项目由PM召开,时间为5月11日晚上10点30分 时长15分钟 任务表格 人员 昨日工作 下一步工作 木鬼 撰写博客整理文档 撰写博客整理文档 swoip 改进界面 为适应新功能 ...

  4. 一个半吊子PM的反思

    故事之源 2019年3月,也就是2016级计算机学院的大三时,软件工程这门课程由选修转为专业必修课,而七个葫芦娃共聚罗杰老师的课堂,组成葫芦娃不想写代码小分队.面临着继承往届项目.完成指定项目和自选项 ...

  5. js获取数组中的最大值/最小值

    目录 前言 1. 使用Math的静态方法max/min 1.1 结合ES6的扩展运算符...使用 1.2 结合apply/call方法来使用 1.3 结合reduce来使用 2. 排序获取 2.1 只 ...

  6. Java NIO Buffer详解

    一.ByteBuffer类型化的put与get方法 /** * ByteBuffer类型化的put与get方法 */ public class NioTest5 { public static voi ...

  7. PHP 命令行参数解析工具类

    <?php/** * 命令行参数解析工具类 * @author guolinchao * @email luoyecb@163.com */class CommandLine{ // store ...

  8. centos7 python2.7升级至python3.5.3版本

    1.wget https://www.python.org/ftp/python/3.5.3/Python-3.5.3.tgz      #下载安装包 2.tar -zxvf Python-3.5.3 ...

  9. 利用FUSE编写自定义的文件系统

    FUSE--用户空间文件系统(Filesystem in Userspace),具体可以度娘,反正是简化了自定义文件系统的复杂度,可以更方便地利用自定义文件系统做一些事情. 一.使用 Python 编 ...

  10. android mk 预编译库

    LOCAL_PATH := $(call my-dir) #include $(CLEAR_VARS) # OpenCV #OPENCV_CAMERA_MODULES:=on #OPENCV_INST ...