runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  710 随笔 :: 0 文章 :: 127 评论 :: 98万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

.net core (.net6) 读取配置文件 appsettings.json

新建个工具类,方便其它地方使用,代码如下

AppHelper:

namespace net6mvc.Utils
{
    public class AppHelper
    {
        private static IConfiguration _config;

        public AppHelper(IConfiguration configuration)
        {
            _config = configuration;
        }

        /// <summary>
        /// 读取指定节点的字符串
        /// </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;
        }
    }
}

appsettings.json 示例如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AppVer": "2022-01-13 21:54",
  "Test": {
    "A": "Hello",
    "B": {
      "C": "World"
    }
  }
}

修改Program.cs

  1. 在CreateBuilder前增加
using net6mvc.Utils;

IConfiguration configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();
  1. 在 CreateBuilder 后增加
builder.Services.AddSingleton (new AppHelper(configuration));

完整代码:



using net6mvc.Utils;

IConfiguration configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddSingleton (new AppHelper(configuration));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

使用

public IActionResult Index()
{
    string a = AppHelper.ReadAppSettings("Test", "A");
    string b = AppHelper.ReadAppSettings("Test", "B", "C");
    ViewBag.Test1 = $"{a} ***** {b}";
    string AppVer = AppHelper.ReadAppSettings("AppVer");
    ViewBag.AppVer = AppVer;
    return View();
}
posted on   runliuv  阅读(1570)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
历史上的今天:
2021-01-13 在阿里云WINDOWS机器上部署的JAVA SpringBoot 时不时的无效 。
点击右上角即可分享
微信分享提示