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

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

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

AppHelper:

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

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

        /// 
        /// 读取指定节点的字符串
        /// 
        /// 
        /// 
        public static string ReadAppSettings(params string[] sessions)
        {
            try
            {
                if (sessions.Any())
                {
                    return _config[string.Join(":", sessions)];
                }
            }
            catch
            {
                return "";
            }
            return "";
        }

        /// 
        /// 读取实体信息
        /// 
        /// 
        /// 
        /// 
        public static List ReadAppSettings(params string[] session)
        {
            List list = new List();
            _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();
}

你可能感兴趣的:(json,.netcore,.net)