zoukankan      html  css  js  c++  java
  • ASP.NET Core 入门教程1 ASP.NET Core 读取配置文件

    ASP.NET Core 对于读取配置文件,和之前.NET Framework 有了很大的区别,下面将介绍一下在学习ASP.NET Core过程中的配置文件的读取操作。

    点击下载源代码

    1、用VS2019新建一个ASP.NET Core Web 应用程序,MVC项目,如下图:

      

      

      

    2、 “key:"value" 格式读取 读取配置文件

    /*
    * 按照关键字直接读取 2种方法 0级目录 型如 “key:"value" 格式
    * "TestReadConfig": "这是从配置文件读取的关键字为【TestReadConfig】的内容。",
    */
    var testReadConfig1 = Configuration.GetValue(typeof(string), "TestReadConfig");
    //或者这种写法也可以
    testReadConfig1 = Configuration.GetValue<string>("TestReadConfig");

    //第二种写法
    var testReadConfig2 = Configuration.GetSection("TestReadConfig").Value;

    3、"Key": {"key": "value" } ==>"ConnectionStrings": {"Default": "Server=;" } 2种方法读取

    /*
    * 按照关键字直接读取 2种方法 1级目录
    * "ConnectionStrings": {"Default": "Server=;" }
    */

    /*
    * 按照关键字直接读取 2种方法 1级目录
    * "ConnectionStrings": {"Default": "Server=;" }
    */

    var connectionStrings1 = Configuration.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value;//默认取第一个
    var connectionStrings2 = Configuration.GetSection("ConnectionStrings:Default").Value;//键值对取值

    /*
    键值对读取方法
    "Student": {
    "Name": "小明",
    "Age": 18
    }
    */
    var keyValueName = Configuration.GetSection("Student:Name").Value;
    var keyValueAge = Configuration.GetSection("Student:Age").Value;

    4、组合实体类

    /*
    * 组合实体类
    * "Student": {
    "Name": "小明",
    "Age": 18
    }
    */

    int age = -99;
    var student = Configuration.GetSection("Student").GetChildren()
    .Select(config => new Student()
    {
    Name = config["Name"],
    Age = int.TryParse(config["Age"], out age) == true ? age : age,
    });

    代码如下:

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Threading.Tasks;
      5 using System.Runtime;
      6 using Microsoft.AspNetCore.Builder;
      7 using Microsoft.AspNetCore.Hosting;
      8 using Microsoft.AspNetCore.HttpsPolicy;
      9 using Microsoft.Extensions.Configuration;
     10 using Microsoft.Extensions.DependencyInjection;
     11 using Microsoft.Extensions.Hosting;
     12 
     13 namespace WebApplicationStudy
     14 {
     15     public class Startup
     16     {
     17         public Startup(IConfiguration configuration)
     18         {
     19             Configuration = configuration;
              
            //加载配置文件方法1
                /*var builder = new ConfigurationBuilder().AddJsonFile("AppSettings.json");
                Configuration = builder.Build();*/
    
                //加载配置文件方法2
                /*Configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("AppSettings.json").Build();*/
    
    
    
     20         }
     21 
     22         public IConfiguration Configuration { get; }
     23 
     24         // This method gets called by the runtime. Use this method to add services to the container.
     25         public void ConfigureServices(IServiceCollection services)
     26         {
     27             services.AddControllersWithViews();
     28         }
     29 
     30         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
     31         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
     32         {
     33             if (env.IsDevelopment())
     34             {
     35                 app.UseDeveloperExceptionPage();
     36             }
     37             else
     38             {
     39                 app.UseExceptionHandler("/Home/Error");
     40                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
     41                 app.UseHsts();
     42             }
     43 
     44             app.UseHttpsRedirection();
     45             app.UseStaticFiles();
     46 
     47             app.UseRouting();
     48 
     49             app.UseAuthorization();
     50 
     51             app.UseEndpoints(endpoints =>
     52             {
     53                 endpoints.MapControllerRoute(
     54                     name: "default",
     55                     pattern: "{controller=Home}/{action=Index}/{id?}");
     56             });
     57             /*
     58             {
     59               "Logging": {
     60                 "LogLevel": {
     61                   "Default": "Information",
     62                   "Microsoft": "Warning",
     63                   "Microsoft.Hosting.Lifetime": "Information"
     64                 }
     65               },
     66               "AllowedHosts": "*",
     67 
     68               "ConnectionStrings": {
     69                 "Default": "Server=;"
     70               },
     71               "TestReadConfig": "这是从配置文件读取的关键字为【TestReadConfig】的内容。",
     72               "Student": {
     73                 "Name": "小明",
     74                 "Age": 18
     75               }
     76             }
     77              */
     78             /*
     79              * 按照关键字直接读取 2种方法 0级目录 型如 “key:"value" 格式
     80              * "TestReadConfig": "这是从配置文件读取的关键字为【TestReadConfig】的内容。",
     81              */
     82             var testReadConfig1 = Configuration.GetValue(typeof(string), "TestReadConfig");
     83             //或者这种写法也可以
     84             testReadConfig1 = Configuration.GetValue<string>("TestReadConfig");
     85 
     86             //第二种写法
     87             var testReadConfig2 = Configuration.GetSection("TestReadConfig").Value;
     88 
     89             /*
     90             * 按照关键字直接读取 2种方法 1级目录
     91             *  "ConnectionStrings": {"Default": "Server=;" }
     92             */
     93             var connectionStrings1 = Configuration.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value;//默认取第一个
     94             var connectionStrings2 = Configuration.GetSection("ConnectionStrings:Default").Value;//键值对取值
     95 
     96 
     97             /*
     98              键值对读取方法
     99               "Student": {
    100                         "Name": "小明",
    101                         "Age": 18
    102                       }
    103              */
    104             var keyValueName = Configuration.GetSection("Student:Name").Value;
    105             var keyValueAge = Configuration.GetSection("Student:Age").Value;
    106 
    107             /*
    108              * 组合实体类
    109              *   "Student": {
    110                         "Name": "小明",
    111                         "Age": 18
    112                       }
    113              */
    114 
    115             int age = -99;
    116             var student = Configuration.GetSection("Student").GetChildren()
    117                 .Select(config => new Student()
    118                 {
    119                     Name = config["Name"],
    120                     Age = int.TryParse(config["Age"], out age) == true ? age : age,
    121                 });
    122 
    123             #region MyRegion
    124             /*var studentIConfigurationSectionList = Configuration.GetSection("Student").GetChildren().ToList<IConfigurationSection>();
    125            if (studentIConfigurationSectionList !=null && studentIConfigurationSectionList.Count>0)
    126            {
    127                foreach (var item in studentIConfigurationSectionList)
    128                {
    129 
    130                }
    131            }*/
    132             #endregion
    133         }
    134 
    135         private class Student
    136         {
    137             public string? Name { get; set; }
    138             public int? Age { get; set; }
    139         }
    140     }
    141 }

    appsettings.json配置文件如下:

     1 {
     2   "Logging": {
     3     "LogLevel": {
     4       "Default": "Information",
     5       "Microsoft": "Warning",
     6       "Microsoft.Hosting.Lifetime": "Information"
     7     }
     8   },
     9 
    10   //方法1 Configuration.GetValue(typeof(string), "TestReadConfig"); 或者 Configuration.GetValue<string>("TestReadConfig");
    11   //方法2  Configuration.GetSection("TestReadConfig").Value;
    12   "AllowedHosts": "*",
    13   "TestReadConfig": "这是从配置文件读取的关键字为【TestReadConfig】的内容。",
    14 
    15   //方法1 Configuration.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value;//默认取第一个
    16   //方法2 Configuration.GetSection("ConnectionStrings:Default").Value; //键值对取值
    17   "ConnectionStrings": {
    18     "Default": "Server=;"
    19   },
    20 
    21   //组合实体类
    22   // int age = -99;
    23   // var student = Configuration.GetSection("Student").GetChildren()
    24   // .Select(config => new Student()
    25   // {
    26   //Name = config["Name"],
    27   // Age = int.TryParse(config["Age"], out age) == true ? age : age,
    28   //});
    29   "Student": {
    30     "Name": "小明",
    31     "Age": 18
    32   }
    33 }

    代码截图如下(图片可能有点小,需要放大来看):

    附上源代码,一起学习

    下载地址:

    https://files-cdn.cnblogs.com/files/ningxt/ASP.NETCore%E5%85%A5%E9%97%A81%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6_20191225_Ning.ASP.NETCore3.Study.7z

  • 相关阅读:
    Anaconda使用命令
    排序算法3--插入排序--希尔排序(缩小增量排序)
    排序算法2--插入排序--折半插入排序
    排序算法1--插入排序--直接插入排序
    排序总结---常用的排序算法总结,java和js实现
    前端兼容性问题
    js对象的几种创建方式和js实现继承的方式[转]
    js原型和原型链[转]
    性能优化的方法
    Http状态码
  • 原文地址:https://www.cnblogs.com/ningxt/p/12096657.html
Copyright © 2011-2022 走看看