从类库中读取配置文件需要添加程序集:
Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
{ "ConnectionStrings": { "Default": "Data Source = DESKTOP-A8O71KP\\MSSQLSERVER2017;Initial Catalog = test; User ID = sa;Password =123" }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.IO;
namespace Common { public class ConfigurationManager { public readonly static IConfiguration Configuration; static ConfigurationManager() {
// Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) .Build(); } public static string conn { get {return Configuration.GetConnectionString("Default"); } } } }
参考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2