本文简单介绍Asp.NetCore取自定义配置信息的方法,要取配置信息首先得有配置文件。
1, 本例新建了一个TimeOut.json配置文件,和其对应的一个TimeOut类
2, 首先在Startup类的构造函数里,加载这个TImeOut.json文件
1 ?public Startup(IHostingEnvironment env) 2 ????????{ 3 ?4 ?5 ????????????var builder = new ConfigurationBuilder() 6 ????????????????.SetBasePath(env.ContentRootPath) 7 ????????????????.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 8 ????????????????.AddJsonFile("TimeOut.json", optional: false, reloadOnChange: true) 9 ????????????????.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)10 ????????????????.AddEnvironmentVariables();11 ????????????Configuration = builder.Build();12 13 ????????}
如上加粗加大的部分。
3,然后在这个方法里添加如下代码
1 ?public void ConfigureServices(IServiceCollection services)2 ????????{3 ???????? services.AddMemoryCache();4 ??????????? services.Configure<TimeOut>(Configuration.GetSection("TimeOut"));5 6 ????????}
4,之后直接在控制器里声明个私有变量在构造器里取得需要的值就行,具体调用代码如下
1 ????????private IMemoryCache _cache;2 ????????private TimeOut _timeOut;3 ????????public UserLoginController(IMemoryCache memoryCache,IOptions<TimeOut> options)4 ????????{5 ????????????_cache = memoryCache;6 ??????????? _timeOut = options.Value;8 ????????}
就是这么简单,但是却很实用,特此给自己留个记录。
Asp.NetCore取配置信息
原文地址:https://www.cnblogs.com/liuqi-chu/p/10373666.html