zoukankan      html  css  js  c++  java
  • asp.net core 读取appsettings.json配置项

    1.新建一个asp.net core 项目

    2.打开appsettings.json,加入配置项

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "StarInfo": { //普通方式
        "Port": 3362
      },
      "Job": {
        "Name": "王小二"
      },
      "JobList": [ //集合方式
        {
          "Name": "王小二",
          "Age": 29,
          "sex": ""
        },
        {
          "Name": "李一一",
          "Age": 22,
          "sex": ""
        }
      ]
    }

    3.创建相应的Model

    Job.cs

     public class Job
    {
         public string Name { get; set; }
    }

    JobItem.cs

    public class JobItem
    {
       public string Name { get; set; }
       public int Age { get; set; }
       public string Sex { get; set; }
    }

    StarInfo.cs

    public class StarInfo
    {
        public int Port { get; set; }
    }

    4.在Startup.cs中加入获取项

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvc();
         //读取配置信息
         services.Configure<StarInfo>(this.Configuration.GetSection("StarInfo"));
         //读取配置信息
         services.Configure<Job>(this.Configuration.GetSection("Job"));
         services.Configure<List<JobItem>>(this.Configuration.GetSection("JobList"));
    }

    5.注入到Controller中

    public class HomeController : Controller
        {
            public StarInfo StarInfoConfig;
            public Job JobConfig;
            public List<JobItem> JobListConfig;
            //重写构造函数,包含注入的配置信息
            public HomeController(IOptions<StarInfo> setting, IOptions<Job> jobsetting, IOptions<List<JobItem>> joblistsetting)
            {
                StarInfoConfig = setting.Value;
                JobConfig = jobsetting.Value;
                JobListConfig = joblistsetting.Value;
            }
            public IActionResult Index()
            {
                string portstr = StarInfoConfig.Port.ToString();
                string jobname = JobConfig.Name;
                string liststr = "";
                JobListConfig.ForEach(item =>
                {
                    liststr += item.Name + "," + item.Age + "," + item.Sex + "|||||";
                });
                ViewBag.portstr = portstr;
                ViewBag.jobname = jobname;
                ViewBag.liststr = liststr;
                return View();
            }
        }

    6.输出结果

     点击下载代码

  • 相关阅读:
    基于Cat的分布式调用追踪
    python3.8.0 Django 开发后端接口api 部署到 Linux Centos7上
    openlayers上添加点击事件
    openlayers在底图上添加静态icon
    vue中使用kindeditor富文本编辑器2
    openlayers绘制点,线,圆等
    openLayers绘制静态底图
    快速调用Android虚拟机
    flutter环境配置window10
    reactjs中配置代理跨域
  • 原文地址:https://www.cnblogs.com/itmu89/p/8310529.html
Copyright © 2011-2022 走看看