jenkins 读取json文件_干货:.net core实现读取appsettings.json配置文件(建议收藏)...
程序员文章站
2023-12-28 15:52:40
...
看好多人不懂在.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
出处:https://www.cnblogs.com/jiyuwu/p/11776044.html
版权申明:本文来源于网友收集或网友提供,如果有侵权,请转告版主或者留言,本公众号立即删除。
推荐阅读
-
jenkins 读取json文件_干货:.net core实现读取appsettings.json配置文件(建议收藏)...
-
.net core读取配置文件appsettings.json
-
.NET Core读取配置文件appsettings.json
-
.NET Core 读取appsettings.json配置文件
-
Asp .Net Core 读取appsettings.json配置文件
-
Asp .Net Core 读取appsettings.json配置文件
-
asp.net core 读取Appsettings.json 配置文件
-
干货:.net core实现读取自定义配置文件,有源代码哦
-
干货:.net core实现读取appsettings.json配置文件(建议收藏)
-
.net core 读取、修改配置文件appsettings.json