zoukankan      html  css  js  c++  java
  • ASP.NET Core读取配置文件

    官方地址

    https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0

    appsetting.josn文件

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=db;Trusted_Connection=True;MultipleActiveResultSets=true"
      },
      "Logging": {
        //Debug中最低输出级别Information
        "Debug": {
          "LogLevel": {
            "Default": "Trace"
          }
        },
        //Console中最低输出级别Trace
        "Console": {
          "LogLevel": {
            "Default": "Information"
          }
        },
        "LogLevel": {
          "Default": "Trace" //日志最低级别
        }
      },
      "AllowedHosts": "*"
    }

     使用IConfiguration获取

    public class HomeController : Controller
    {
            private readonly IConfiguration  _configuration;
            public HomeController(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            public IActionResult Config()
            {
               var config = _configuration["AllowedHosts"];
                return Json(config);
            }
    }

     添加包

    Install-Package Microsoft.Extensions.Configuration
    Install-Package Microsoft.Extensions.Configuration.Json

    实例化对象获取

    public IActionResult Config()
    {
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        //获取根目录
        configurationBuilder.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
        //构建configurationBuilder对象
        var configuration = configurationBuilder.Build();
        //获取字符串
        var conectString = configuration.GetConnectionString("DefaultConnection");
        //获取AllowedHosts
        var AllowedHosts = configuration["AllowedHosts"];
        //获取Loggin下的Default
        var Default = configuration["Logging:Console:LogLevel:Default"];
    
        return Content(Default);
    }

     appsetting.josn中的json数据

    "Student": [
        {
          "name": "张三",
          "age": "36",
          "hobby": [
            {
              "ballGame": "Basketball"
            },
            {
              "skill": "sing"
            }
          ]
        },
        {
          "name": "李四",
          "age": "23"
        }
      ]

    读取

     //获取张三的年龄
    var name= configuration["Student:0:age"];
    
    //获取张三唱歌的爱好
    var sing = configuration["Student:0:hobby:1:skill"];
  • 相关阅读:
    LeetCode 258 Add Digits
    LeetCode 231 Power of Two
    LeetCode 28 Implement strStr()
    LeetCode 26 Remove Duplicates from Sorted Array
    LeetCode 21 Merge Two Sorted Lists
    LeetCode 20 Valid Parentheses
    图形处理函数库 ImageTTFBBox
    php一些函数
    func_get_arg(),func_get_args()和func_num_args()的用法
    人生不是故事,人生是世故,摸爬滚打才不会辜负功名尘土
  • 原文地址:https://www.cnblogs.com/-zzc/p/14199102.html
Copyright © 2011-2022 走看看