1. 程式人生 > >.net core 修改appsettings.json

.net core 修改appsettings.json

true sta alt sof ros pub rec pri clas

.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();
        }

類庫中

            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效果如截圖

        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
    技術分享圖片

WriteJSON修改appsettings.json

        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