如圖:
一、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; } } }