可以在appsettings中配置数据量连接字符串等数据,便于项目发布后的配置
首先,创建 ConfigHelper类
namespace TestProject.services { public class ConfigHelper { private static IConfiguration _config; public ConfigHelper(IConfiguration configuration) { _config = configuration; } /// <summary> /// 读取appsettings.json文件中指定节点信息 /// </summary> /// <param name="sessions"></param> /// <returns></returns> public static string ReadAppSettings(params string[] sessions) { try { if (sessions.Any()) { return _config[string.Join(":",sessions)]; } } catch { return ""; } return ""; } /// <summary> /// 读取实体信息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="session"></param> /// <returns></returns> public static List<T> ReadAppSettings<T>(params string[] session) { List<T> list = new List<T>(); _config.Bind(string.Join(":",session),list); return list; } } }
然后在Program.cs中添加如下代码注入服务
var builder = WebApplication.CreateBuilder(args); IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); builder.Services.AddSingleton(new ConfigHelper(configuration));
在 appsettings.json中添加如下代码
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "Test": { "testStr1": "testvalue1", "testStr2": "testvalue2" }, }
最后,可以在项目的任意地方读取配置文件数据
string str = ConfigHelper.ReadAppSettings("Test", "testStr1");
可以获取 str 的值为 testvalue1。
本文参考简书文章,写文章 - .net core (.net6) 读取配置文件 appsettings.json - 简书 (jianshu.com)
感谢原作者。
标签:web,读取,配置文件,appsettings,ConfigHelper,public,string From: https://www.cnblogs.com/kevinN/p/16739510.html