.Net Core 获取 appsettings.json 数据

一、前言

  这是我学习的笔记,如果您看到有不对的地方,欢迎评论区指正!很多时候,我们将系统的配置都放入配置文件中,主要的目的就是为了方便修改!这就是我学习的目的。

二、具体学习

  在学习获取 AppSettings.json 的数据,首先我们需要了解 Configuration、ConfigurationBuilder 和 ConfigurationProvider .其中 ConfigurationProvider  对象承载着在编程中使用的配置信息,由ConfigurationBuilder 来完成,它利用 ConfigurationProvider 提取源数据将其转化为 Configuration 对象。

我的配置文件 appsettings.json 文件如下

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "asdfasdfasdfasdfasdfas"
  },
  "cnblogs": "My CNBlogs Address:https://www.cnblogs.com/gzbit-zxx/",
  "AppSettings": {
    "HttpUrl": "http://www.gzbit.com",
    "Copyright": "gzbit"
  },
  "AllowedHosts": "*",
  "Person": [
    {
      "name": "xfmtl",
      "company": "gzbit",
      "address": [
        {
          "province": "Guizhou Province",
          "city": "Guiyang City"
        },
        {
          "province": "Yunnan Province",
          "city": "Wuhua District"
        }
      ]
    },
    {
      "name": "C# Study",
      "adress": "Microsoft"
    }
  ],
  "Book": {
    "name": "C# Program",
    "publish": "2020-08"
  }

}

第一种直接使用方式

直接在 Controller 通过 ConfigurationBuilder 方式获取.

using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace WebApplication1.Controllers
{
    public class ConfigController : Controller
    {
        public IActionResult Index()
        {
            //加载配置文件
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            //添加配置文件路径
            configurationBuilder.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

            var configuration = configurationBuilder.Build();

            //获取博客园地址
            var cnblogs = configuration["cnblogs"];

            //获取Book名称
            var bookname = configuration.GetValue<string>("Book:name");

            //获取幸福摩天轮的第一地区名称
            var addressName = configuration.GetValue<string>("Person:0:address:1:city");

            //获取C# 学习的名称
            var cname = configuration.GetValue<string>("Person:1:name");

            //获取所在公司
            var companyName= configuration["AppSettings:Copyright"];

            return Content(cnblogs);
        }
    }
}

测试案例截图

 

 第二种方式在 Startup.cs 中 Startup方法中配置

  (1)、添加一个 Book.cs 类

namespace WebApplication1.Common
{
    /// <summary>
    /// 书
    /// </summary>
    public class Book
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 发布时间
        /// </summary>
        public string Publish { get; set; }
    }
}

  (2)、在 Startup.cs 中添加代码

using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication1.Common;

namespace WebApplication1
{
    public class Startup
    {
        //定义 _configuration
        public IConfiguration _configuration;
        public Startup()
        {
            //加载配置文件
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            //添加配置文件路径
            configurationBuilder.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

            //加载文件
             _configuration = configurationBuilder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            //获取配置文件中 Book 数据
            services.Configure<Book>(_configuration.GetSection("Book"));
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

  (3)、在 Controller 中调用

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WebApplication1.Common;

namespace WebApplication1.Controllers
{
    public class ConfigController : Controller
    {
        //定义
        private readonly Book _book;

        /// <summary>
        /// 构造函数中注入Book
        /// </summary>
        /// <param name="options"></param>
        public ConfigController(IOptions<Book> options) {
            _book = options.Value;
        }
        public IActionResult Index()
        {
            //获取书本名称
            var name = _book.Name;

            //获取书本的发布时间
            var publish = _book.Publish;
          
            return Content(_book.Name);
        }
    }
}

  (4)、案例截图

 

 第三种使用方式,也是 .net core web 默认的方式。

  (1)、在 Startup.cs 中代码如下,同样我们也需要创建相应的类。如 Book.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication1.Common;

namespace WebApplication1
{
    public class Startup
    {
        // 定义 Configuration
        public IConfiguration Configuration { get; }
        /// <summary>
        /// 依赖注入 IConfiguration
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            //获取配置文件中 Book 数据
            services.Configure<Book>(Configuration.GetSection("Book"));
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

  (2)、在 Controller 使用

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WebApplication1.Common;

namespace WebApplication1.Controllers
{
    public class ConfigController : Controller
    {
        //定义
        private readonly Book _book;

        /// <summary>
        /// 构造函数中注入Book
        /// </summary>
        /// <param name="options"></param>
        public ConfigController(IOptions<Book> options) {
            _book = options.Value;
        }
        public IActionResult Index()
        {
            //获取书本名称
            var name = _book.Name;
            
            //获取书本的发布时间
            var publish = _book.Publish;
          
            return Content(_book.Name);
        }
    }
}

 这就是读取 appsettings 的方式,重点还是读取字符串的三种方式:字符串读取:configuration["cnblogs"]、configuration.GetValue<string>("Book:name")对象读取Configuration.GetSection("Book") 。

posted @ 2020-10-17 14:42  周兴兴  阅读(9033)  评论(4编辑  收藏  举报