.net core 读取配置
在.net core中读取配置,我们通常的做法是通过IConfiguration进行读取,但使用的过程中感觉不是很方便。有一种通过映射的方式来读取配置,更加简洁明了
1.在appsettings.json中配置一个节点
"JWT": { "Issuer": "http://localhost:49999", //Token发布者 "Audience": "http://localhost:49999", //Token接受者 "IssuerSigningKey": "123456888jdij9999998989efect", //密钥 "AccessTokenExpiresMinutes": "30" //过期时间 }
2.新建节点对应的实体类
public class JWTModel { public string Issuer { get; set; } public string Audience { get; set; } public string IssuerSigningKey { get; set; } public int AccessTokenExpiresMinutes { get; set; } }
3.在ConfigureServices中完成注册
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<JWTModel>(Configuration.GetSection("JWT")); //JWT为appsettings.json中的节点名称 }
4.使用配置
private IOptions<JWTModel> _options; public TokenHelper(IOptions<JWTModel> options) //通过构造函数注入 { _options = options; } public string GetKey() { string key = _options.Value.IssuerSigningKey; return key; }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号