乾貨:.net core實現讀取appsettings.json配置文件(建議收藏)

原文: 乾貨:.net core實現讀取appsettings.json配置文件(建議收藏)

看好多人不懂在.NET CORE中如何讀取配置文件,我這裏分兩篇,這一篇介紹怎樣經過appsettings.json配置讀取文件信息。這裏我會教你們兩種方式:html

第一種直接放到通用類庫,那裏想調往那調。git

1.編輯咱們的appsettings.json文件github

複製代碼
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "TestConnection": "server=123;User ID=jiyuwu;Password=123456;database=jiyuwu;",
    "Redis": "127.0.0.1:6379"
  },
  "AllowedHosts": "*"
}
複製代碼

 

 

 2.通用類庫Common添加引用類庫Microsoft.Extensions.Configuration.Json並添加AppSettingsHelper.cssql

Install-Package Microsoft.Extensions.Configuration.Json -Version 3.0.0

複製代碼
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common
{
        public class AppSettingsHelper
        {
            public static IConfiguration Configuration { get; set; }
            static AppSettingsHelper()
            {
                //ReloadOnChange = true 當appsettings.json被修改時從新加載            
                Configuration = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
                .Build();
            }

        }
    }
複製代碼

3.調用json

string sqlString= AppSettingsHelper.Configuration.GetConnectionString("TestConnection");
string sqlString1 = AppSettingsHelper.Configuration["Logging:LogLevel:Default"];

 

 

第二種直接讀文件調用。app

1.引用類庫並讀取文件獲取配置測試

Install-Package Microsoft.Extensions.Configuration.Json -Version 3.0.0
複製代碼
public IConfiguration Configuration;
public void TestAppSettings()
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            Configuration = builder.Build();
            string sqlString2 = Configuration["Logging:LogLevel:Default"];
        }
複製代碼

 

 

簡單介紹下原理:ui

咱們經過ConfigurationBuilder對象來建立ConfigurationRoot對象,並用其來讀取配置。SetBasePath()方法是用來設置咱們配置對象須要的配置文件的基礎路徑,好比咱們將基礎路徑設置爲C:\TemplateCore\TemplateCore,那麼他讀取咱們的配置文件appsettings.json的路徑將是C:\TemplateCore\TemplateCore\appsettings.jsonthis

 

 

開源地址:https://github.com/jiyuwu/TemplateCorespa

測試瀏覽效果:http://127.0.0.1:1994/home/TestAppSettings

 

 幫助到你的話請點個推薦,謝謝。

相關文章
相關標籤/搜索