看好多人不懂在.NET CORE中如何读取配置文件,我这里分两篇,这一篇介绍怎样通过appsettings.json配置读取文件信息。这里我会教大家两种方式:
第一种直接放到通用类库,那里想调往那调。
1.编辑我们的appsettings.json文件
{ "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.cs
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.调用
string sqlString= AppSettingsHelper.Configuration.GetConnectionString("TestConnection"); string sqlString1 = AppSettingsHelper.Configuration["Logging:LogLevel:Default"];
第二种直接读文件调用。
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"]; }
简单介绍下原理:
我们通过ConfigurationBuilder
对象来创建ConfigurationRoot
对象,并用其来读取配置。SetBasePath()
方法是用来设置我们配置对象需要的配置文件的基础路径,比如我们将基础路径设置为C:\TemplateCore\TemplateCore
,那么他读取我们的配置文件appsettings.json
的路径将是C:\TemplateCore\TemplateCore\appsettings.json
开源地址:https://github.com/jiyuwu/TemplateCore
测试浏览效果:http://127.0.0.1:1994/home/TestAppSettings
帮助到你的话请点个推荐,谢谢。