asp.net core 读取Appsettings.json 配置文件

Appsettings.json 配置

很明显这个配置文件就是一个json文件,并且是严格的json文件,所有的属性都需要添加“”引号;
面给出一段自定义的配置文件吧	
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "StarInfo": {
    "Port": 4567
  }
}

定义实体

需要定义一个实体,类型与配置文件匹配,以便将配置文件中的json转成C#中的实体进行操作
实体的代码如下
  public class StarInfo
    {
        public int Port { get; set; }
    }

在StartUp时读取配置信息

在startup的ConfigureServices方法中读取配置信息
样例代码:
   // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            //读取配置信息
            services.Configure<StarInfo>(this.Configuration.GetSection("StarInfo"));
        }

修改你的Controller,通过构造函数进入配置信息

?先说一个疑问:我没有搞清楚这个构造函数的注入是在哪个接口内完成的,等有时间看一下源码吧,否则这种导出都是注入的代码理解起来还是有点困难。

我这里是直接在HomeController中进行修改的,样例代码如下:
 public class HomeController : Controller
    {
    //定义配置信息对象
        public StarInfo StarInfoConfig;
        //重写构造函数,包含注入的配置信息
        public HomeController(IOptions<StarInfo> setting) {
            StarInfoConfig = setting.Value;
        }
        //Action
        public IActionResult Index()
        {
        //读取配置信息,这里也就是使用的地方了
            ViewData["Port"] = StarInfoConfig.Port;
            return View();
        }

总结

就这样一个简单的配置文件读取就完成了。
但是这也仅仅是一个demo,在项目中这样的读取太不实用了,以后我会针对一个项目写一整套完成的Asp.net Core做项目的系列文章,希望大家能够关注。

V2

做了一年的core项目,在这里补充一个读取配置文件的方法
将StartUp文件的Configuration属性设置成public static(不推荐)

var values = StartUp.Configration["App:SelfUrl"]

也可以通过构造方法注入IConfigration(推荐)

var values = Configration["App:SelfUrl"];//Configration 注入对象

引用
特别感谢广大网友的知识分享
感谢dudu的网络文章
感谢Artech的网络文章

原文地址:https://www.cnblogs.com/xiaoch/p/13417951.html