.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(); } }
复制代码

 

posted @   派大没有星  阅读(387)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示