webApi.Net6读取配置文件
作者:admin 来源:原创 2023/3/17 16:31:56

一、在appsettings.json中增加属性字段:app。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "app": {
    "id": "1",
    "name": "名称"
  }
}

二、在Program.cs中读取

string id = builder.Configuration.GetSection("app")["id"];
 string name = builder.Configuration.GetSection("app")["name"];
三、在控制器中读取

    首先改造构造函数,形参增加IConfiguration。

        private readonly ILogger<WeatherForecastController> _logger;
        private IConfiguration Configuration;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
        {
            _logger = logger;
            this.Configuration = configuration;
        }
在方法中读取:
            string id = Configuration.GetSection("app")["id"];
            string name = Configuration.GetSection("app")["name"];
            //或
            string id2= Configuration["app:id"];
            string name2 = Configuration["app:name"];
四、直接序列化为对象

    定义类appModel:

public class appModel
    {
        public string id { get; set; }
        public string name { get; set; }
    }
    在Program.cs中读取
//使用Get序列化成为对象
            appModel appModel = builder.Configuration.GetSection("app").Get<appModel>();
            //或者使用bind函数
            appModel appModel1 = new appModel();
            builder.Configuration.GetSection("app").Bind(appModel1);

    我已将代码上传,下载码是:583B8232C0 

    下载码是啥?如何下载=》点击查看

称      呼:
联系方式:
您的评论:
技术支持:l.w.dong@qq.com www.luweidong.cn
广州市   wx:lwdred
Copyright © 2014 三味书屋 All Rights Reserved
技术支持:l.w.dong@qq.com  sitemap xml  sitemap html

粤公网安备44010602011869号

粤ICP备13031080号-1