配置文件
{
"IdentityServer": {
"Authority": "http://localhost:8501",
"ApiName": "net7_microservice"
},
"Service": {
"IP": "localhost",
"Port": "8503",
"Name": "NET7Service"
},
"Consul": {
"IP": "localhost",
"Port": "8500"
}
}
工具类:AppSettingsHelper
/// <summary>
/// 配置帮助类
/// </summary>
public class AppSettingsHelper
{
static IConfiguration _config;
public AppSettingsHelper(IConfiguration configuration)
{
_config = configuration;
}
/// <summary>
/// 获取键的值
/// </summary>
/// <param name="key">键</param>
/// <param name="IsConn">是否为数据库连接字符串</param>
/// <returns></returns>
public static string Get(string key, bool IsConn = false)
{
string value;
try
{
if (key.IsNull()) return null;
if (IsConn)
{
value = _config.GetConnectionString(key);
}
else
{
value = _config[key];
}
}
catch (Exception)
{
value = null;
}
return value;
}
public static string Get(params string[] sessions)
{
try
{
if (sessions.Any())
{
return _config[string.Join(":", sessions)];
}
}
catch
{
return null;
}
return null;
}
public static string Get(string key)
{
try
{
if (key.IsNull()) return null;
return _config[key];
}
catch
{
return null;
}
}
public static List<T> Get<T>(params string[] session)
{
var list = new List<T>();
_config.Bind(string.Join(":", session), list);
return list;
}
public static IConfigurationSection GetSection(string key)
{
try
{
return _config.GetSection(key);
}
catch
{
return null;
}
}
}
注册:Program.cs文件的最上方添加如下代码:
var builder = WebApplication.CreateBuilder(args);
var basePath = AppContext.BaseDirectory;
#region 引入配置文件
var _config = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
builder.Services.AddSingleton(new AppSettingsHelper(_config));
#endregion
用法:
AppSettingsHelper.Get("IdentityServer:ApiName");
1