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

問題引出

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

有Web.config時,咱們須要讀到配置文件時,通常是這樣的:json

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

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

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

 

若是在Controller須要讀取配置文件,在Startup.cs文件中註冊相關服務,能夠相似於註冊context同樣:測試

// 一、註冊相關服務,相似於以下的XXXContext的例子

services.AddDbContext<XXXContext>(XXX 。。。

 

// 二、controller讀取

而後在具體controller的構造函數中做爲參數獲取。

相似於:

private IConfiguration _configuration;

public XXXController(IConfiguration configuration)

{
    _configuration = configuration;
}

 

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

這種方式引出兩個問題:spa

一、多數controller是須要讀取context的,但不是每一個controller都須要讀取配置文件,這種方式不夠簡潔.net

二、若是咱們須要在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. 系列文章列表:http://www.javashuo.com/article/p-yaakbokp-y.html

 

相關文章
相關標籤/搜索