問題引出
ASP.NET Core 默認將 Web.config移除了,將配置文件統(tǒng)一放在了 xxx.json 格式的文件中。
有Web.config時,我們需要讀到配置文件時,一般是這樣的:
var value1= ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
這個ConfigurationManager是在System.Configuration 命名空間下的。
很不幸,默認情況下這個方法也不能用了。
?
如果在Controller需要讀取配置文件,在Startup.cs文件中注冊相關(guān)服務,可以類似于注冊context一樣:
// 1、注冊相關(guān)服務,類似于如下的XXXContext的例子 services.AddDbContext<XXXContext>(XXX 。。。 //
2、controller讀取 然后在具體controller的構(gòu)造函數(shù)中作為參數(shù)獲取。 類似于: private IConfiguration
_configuration;public XXXController(IConfiguration configuration) {
_configuration= configuration; }
?
具體實現(xiàn)方式已有多篇文章講解,請自行搜索,不再贅述。
這種方式引出兩個問題:
1、多數(shù)controller是需要讀取context的,但不是每個controller都需要讀取配置文件,這種方式不夠簡潔
2、如果我們需要在controller之外的其他類文件中讀取呢?
?
我們仿照ConfigurationManager讀取Web.config中文件的方式,自定義一個MyConfigurationManager 類。
我直接在上一篇文章中的示例程序添加演示。
?
詳細步驟
步驟一:準備好素材,appsettings.json添加配置項
? "GrandParent_Key": { "Parent_Key": { "Child_Key": "value1" } },
? "Parent_Key": { "Child_Key": "value2" },
? "Child_Key": "value3"
?
?
步驟二:添加 MyConfigurationManager.cs
?
?
/// <summary> /// 獲取自定義的 json 配置文件 /// </summary> static class
MyConfigurationManager {public static IConfiguration AppSetting { get; } static
MyConfigurationManager() {// 注意:2.2版本的這個路徑不對 會輸出 xxx/IIS Express...類似這種路徑, //
等3.0再看有沒其他變化 string directory = Directory.GetCurrentDirectory(); AppSetting =
new ConfigurationBuilder() .SetBasePath(directory) .AddJsonFile("
myAppSettings.json") .Build(); } }
?
?
步驟三:調(diào)用
我們?nèi)omeController中添加一個測試方法
public IActionResult ConfigTest() { string value1 =
MyConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"];
string value2 = MyConfigurationManager.AppSetting["Parent_Key:Child_Key"];
string value3 = MyConfigurationManager.AppSetting["Child_Key"]; return View(); }
?
加個斷點調(diào)試一下,可以看到輸出了想要的結(jié)果。
?
總結(jié)
通過自定義的Configuration方法可以方便讀取json文件。
獲取配置文件路徑時,AppContext.BaseDirectory在 .net core 2.2和2.1不一樣,
如果事先用的2.2模板,需要右鍵項目,將target framework設(shè)為2.1
?
?
P.S. 路徑獲取這塊給出一個通用的方法,這樣2.1和2.2就都滿足了,如下:
var fileName = "appsettings.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}"; }
?
?
祝 學習進步 :)
?
P.S. 系列文章列表:https://www.cnblogs.com/miro/p/3777960.html
<https://www.cnblogs.com/miro/p/3777960.html>
?
?
熱門工具 換一換