Optimistic people do not know how to read the configuration file in the .NET CORE, I have here the two points, on an introductory information on how to read the configuration file by appsettings.json. This will teach you a custom configuration file:
1. Create a configuration file in the project
{ "FileMap": { "ImgPath": "D:\\myfile\\misc\\NPSPower\\TemplateCore\\TemplateCore\\wwwroot\\UpImg\\", "ImgWeb": "http://127.0.0.1:1994/UpImg/", "FilePath": "D:\\myfile\\misc\\NPSPower\\TemplateCore\\TemplateCore\\wwwroot\\UpFile\\", "FileWeb": "http://127.0.0.1:1994/UpFile/", "VideoPath": "D:\\myfile\\misc\\NPSPower\\TemplateCore\\TemplateCore\\wwwroot\\UpVideo\\", "VideoWeb": "http://127.0.0.1:1994/UpVideo/", "Web": "http://127.0.0.1:1994/" } }
2. The reference library Microsoft.Extensions.Configuration.Json operations and create a profile class ConfigHelper.cs
Install-Package Microsoft.Extensions.Configuration.Json -Version 3.0.0
the using Microsoft.Extensions.Configuration; the using the System; the using the System.Collections.Generic; the using the System.IO; the using the System.Text; namespace the Common { public class ConfigHelper { Private static IConfiguration _configuration; static ConfigHelper () { // current directory or Looking root directory file var fileName = " Config / ManagerConfig.json " ; var directory = AppContext.BaseDirectory; directory = directory.Replace ("\\", "/"); var filePath = $"{directory}/{fileName}"; if (!File.Exists(filePath)) { var length = directory.IndexOf("/bin"); filePath = $"{directory.Substring(0, length)}/{fileName}"; } var builder = new ConfigurationBuilder() .AddJsonFile(filePath, false, true); _configuration = builder.Build(); } public static string GetSectionValue(string key) { return _configuration.GetSection(key).Value; } } }
3. Read the configuration file in the project
string ImgPath = ConfigHelper.GetSectionValue("FileMap:ImgPath"); return ImgPath;
Open Source Address: https://github.com/jiyuwu/TemplateCore
Testing browsing effect: http://127.0.0.1:1994/home/TestConfig
To help you, then please recommend one, thank you.