.net core 读取appsettings文件

首先需要说明的是 .net core 2.1 中默认已经注入了读取appsettings.json的方法, 我们只要使用就可以了,例如下面的controller里面的代码

 private readonly IConfiguration configuration;
        public StudentController(IConfiguration conf)
        {
            configuration = conf;
        }

        [HttpGet("get2")]
        public String TestGet()
        {   
            var conn = configuration["ConnectionStrings:DefaultConnection"].ToString();
            var stu = configuration["Student"];
            var db = configuration["DbConnect"];
            return conn + "---" + stu + "---" + db;
        }

下面的是 appsettings.json 的代码

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3306;user=root;password=root;database=test"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Student": "Stdent",
  "DbConnect": "DbConnect",
  "AllowedHosts": "*"

}

下面的是第二种方法,直接把 IConfiguration  当做参数传递,然后后直接试用就好了,很方便,记得要把 [FromServices] 放到参数的前面,否则得不到数据

        [HttpGet("get2")]
        public String TestGet ([FromServices] IConfiguration configuration)
        {   
            var conn = configuration["ConnectionStrings:DefaultConnection"].ToString();
            var stu = configuration["Student"];
            var db = configuration["DbConnect"];
            return conn + "---" + stu + "---" + db;
        }

不需要在另外的搞注入,不需要在start里面写代码,我用的.net core 的2.1 的版本

你可能感兴趣的:(.net,core,.netcore,linq,c#)