.NETCore WebApi框架:从appsettings.json 读取参数配置
.NETCore WebApi框架:从appsettings.json 读取参数配置
appsettings.json
.NETCore WebApi项目中我们将把配置文件统一放在appsettings.json文件中,如下图:
配置信息模型定义
定义实体类模型用于读取配置文件的参数值
C# 全选
/// <summary>
/// 缓存设置,用于加载appsettings.json配置文件的Cache配置信息
/// </summary>
public class CacheOptions
{
public CacheType CacheType { get; set; }
public string RedisEndpoint { get; set; }
}
C# 全选
/// <summary>
/// 用于加载appsettings.json配置文件的jwt配置信息
/// </summary>
public class JwtOptions
{
[Display(Name = "Secret Key jwt令牌加密秘钥")]
public string Secret { get; set; }
[Display(Name = "Access Expire Hours 访问令牌的有效截止时间")]
public int AccessExpireHours { get; set; }
[Display(Name = "Refresh Expire Hours 刷新令牌的有效截止时间")]
public int RefreshExpireHours { get; set; }
[Display(Name = "Issuer 发送方")]
public string Issuer { get; set; }
[Display(Name = "Audience 接收方")]
public string Audience { get; set; }
}
读取配置信息
C# 全选
public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
{
hostBuilder.ConfigureServices((context, services) =>
{
services.Configure<CacheOptions>(context.Configuration.GetSection("Cache"));
var option = context.Configuration.GetSection("Cache").Get<CacheOptions>();
}
}
C# 全选
public static IServiceCollection AddJwtBearer(this IServiceCollection services, IConfiguration configuration, string sectionName)
{
//获取jwt参数配置
services.Configure<JwtOptions>(configuration.GetSection(sectionName));
var myOptions = configuration.GetSection(sectionName).Get<JwtOptions>();
}
封装GlobalAppSettings公共静态类
C# 全选
/// <summary>
/// 获取appsettings.json的配置信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sectionName"></param>
/// <returns></returns>
public static T GetSettings<T>(string sectionName)
{
//实例化IConfiguration接口
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var configRoot = builder.Build();
var section = configRoot.GetSection(sectionName);
return section.Get<T>();
}
读取配置信息:
C# 全选
var options = GlobalAppSettings.GetSettings<CacheOptions>("Cache");
var options = GlobalAppSettings.GetSettings<JwtOptions>("jwt");
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网