.Net Core中获取appsettings.json中的节点数据
获取ConnectionStrings节点数据
//appsettings.json { "ConnectionStrings": { //DEV "DbConn": "Server=**;Integrated Security=no;User ID=**;PWD=**;initial catalog=DB**;MultipleActiveResultSets=true;Max Pool Size=1024;Min Pool Size=10;Pooling=true;" //QA //PROD }, "ErrorPage": "/Error/Error", "Environment": "DEV" }
//startup.cs
public Startup(IConfiguration configuration) //依赖注入 { _configuration = configuration; } public IConfiguration _configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { string _conn; //config db try {
//GetSection("Environment")获取Environment节点的数据 if (_configuration.GetSection("Environment").Value.Equals("PROD", StringComparison.OrdinalIgnoreCase)) { var service = new DecryptService("ProjectICE_Portal"); _conn = service.Decrypt(_configuration.GetConnectionString("DbConn"));//加密获取节点数据 } else { _conn = _configuration.GetConnectionString("DbConn");//非加密 } } catch (Exception ex) { throw new Exception($"Database connection initialization failed: {ex.Message}{ex.StackTrace}"); } }
第二种比较实用的方法
//Appsettings.json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning" } }, "AllowedHosts": "*", "student": { "name": "小明", "age": 17, "classname": "5班" } } //新建一个实体类 实体类的属性和配置文件的配置项一致 public class student { public string name { get; set; } public int age { get; set; } // public string classname { get; set; } } //Startup.cs //services.AddOptions(); 这两个必须在AddMvc上面 services.Configure<student>(Configuration.GetSection("student")); services.AddMvc();
//Controller 依赖注入 using Microsoft.Extensions.Options; public class OneController : Controller { private readonly IOptions<student> _log; public OneController(IOptions<student> logs) { _log = logs; } public IActionResult Index() { var a = _log.Value; ViewBag.a = a.name; //"小明" return View(); } }
分类:
3001-.NET Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现