MVC + EFCore 完整教程19-- 最簡方法讀取json配置:自定義configuration讀取配置文件


問題引出

ASP.NET Core 默認將 Web.config移除了,將配置文件統一放在了 xxx.json 格式的文件中。

有Web.config時,我們需要讀到配置文件時,一般是這樣的:

var value1= ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;

這個ConfigurationManager是在System.Configuration 命名空間下的。

很不幸,默認情況下這個方法也不能用了。

 

如果在Controller需要讀取配置文件,在Startup.cs文件中注冊相關服務,可以類似於注冊context一樣:

// 1、注冊相關服務,類似於如下的XXXContext的例子

services.AddDbContext<XXXContext>(XXX 。。。

 

// 2、controller讀取

然后在具體controller的構造函數中作為參數獲取。

類似於:

private IConfiguration _configuration;

public XXXController(IConfiguration configuration)

{
    _configuration = configuration;
}

 

具體實現方式已有多篇文章講解,請自行搜索,不再贅述。

這種方式引出兩個問題:

1、多數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();

        }

    }

 

 

步驟三:調用

我們去HomeController中添加一個測試方法

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

}

 

加個斷點調試一下,可以看到輸出了想要的結果。

 

總結

通過自定義的Configuration方法可以方便讀取json文件。

獲取配置文件路徑時,AppContext.BaseDirectory在 .net core 2.2和2.1不一樣,

如果事先用的2.2模板,需要右鍵項目,將target framework設為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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM