分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

Asp.NetCore取配置信息

发布时间:2023-09-06 02:33责任编辑:傅花花关键词:配置

   本文简单介绍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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved