如图:
一、appsettings.json
{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*","SqlServer": {"Server": "192.168.1.10","Database": "dbname","UserId": "userid","Password": "password"} }
二、AppHepler.cs
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;}}
三、Program.cs
using ElecInvoice.Common; using log4net.Config;var builder = WebApplication.CreateBuilder(args);// Add services to the container.//读取 appsettings.json IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); builder.Services.AddSingleton(new AppHelper(configuration));//AppHelper为读取appsettings.json的实体类 builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();// 配置 log4net XmlConfigurator.Configure(new FileInfo("log4net.config"));var app = builder.Build();// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) {app.UseSwagger();app.UseSwaggerUI(); }app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
四、用法 SqlDB.cs
public class SqlDB{public static string sqlStr = @$" Server={AppHelper.ReadAppSettings("SqlServer:Server")};Database={AppHelper.ReadAppSettings("SqlServer:Database")};User Id={AppHelper.ReadAppSettings("SqlServer:UserId")};Password={AppHelper.ReadAppSettings("SqlServer:Password")};";public static DataTable Query(string sql){try{using (SqlConnection conn = new SqlConnection(sqlStr)){conn.Open();SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);DataTable dt = new DataTable();adapter.Fill(dt);return dt;}}catch (Exception ex){throw ex;}}}