NET6 web项目读取 appsettings配置文件

可以在appsettings中配置数据量连接字符串等数据,便于项目发布后的配置

首先,创建 ConfigHelper类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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)

感谢原作者。

posted @   VTech_kevin  阅读(645)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示