ASP.NET Core--配置文件

news/2024/7/8 3:52:40

文章目录

  • 配置文件
    • 添加配置文件
    • 读取配置文件
      • 控制台读取配置文件**
      • 控制器中读取
      • 对象读取
    • 自定义配置文件
    • 多环境配置文件

配置文件

添加配置文件

在项目目录下有个 appsettings.json ,我们先来操作这个文件。

在appsettings.json 添加如下两个节点。

{
  "Data": "LineZero",
  "ConnectionStrings": {
    "DefaultConnection": "数据库1",
    "DevConnection": "数据库2"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

读取配置文件

配置文件的读取都是通过一个Configuration对象来读取。具体来说,Configuration对象实际指ConfigurationRoot和ConfigurationSection两个类型。配置文件中根节点所在的Configuration对象被称为ConfigurationRoot,除此之外的其他Configuration对象则被称为ConfigurationSection,配置模型分别定义了接口IConfigurationRoot和IConfigurationSection来表示它们,这两个接口都是IConfiguration的继承者
在这里插入图片描述
Configuration对象是由ConfigurationBuilder创建的,
而原始的配置信息来源是通过ConfigurationSource获取的的,
所以读取配置信息时首先需要一个 ConfigurationRoot对象,所以读取过程是:先创建一个ConfigurationBuilder对象,在ConfigurationBuilder对象上添加或者注册数据源 ConfigurationSource(可以注册一个或者多个), 最后调用Buid()方法,来实现我们需要的Configuration对象的一个实例。

即:

  IConfiguration config = new ConfigurationBuilder()
                    //注册一个或者多个ConfigurationSource对象,在此注册一个内存配置来源
                    .Add(
                             ……
                    ).Build();  //通过Buid()方法,创建 Configuration对象

注册多个配置来源

  var builder = new ConfigurationBuilder();
    builder.AddInMemoryCollection(dict);//内存配置源
    builder.SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");//注册当前路径下的配置源

在这里插入图片描述

控制台读取配置文件**

   var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");
            Configuration = builder.Build();
            Console.WriteLine($"Name = {Configuration["Data"]}");
            Console.WriteLine($"hold:ceshi = {Configuration["hold:ceshi"]}");
            Console.WriteLine($"ConnectionStrings:NetCoreForWebContext={Configuration["ConnectionStrings:NetCoreForWebContext"]}");
            Console.WriteLine($"Logging:LogLevel:Default={Configuration["Logging:LogLevel:Default"]} ");
            Console.WriteLine($"Logging:IncludeScopes={Configuration["Logging:IncludeScopes"]} ");
            Console.WriteLine($"list:NUM={Configuration["list:NUM"]} ");
            Console.WriteLine($"list:Age={Configuration["list:Age"]} ");
            Configuration["list:Age"] = "99";//并不能更新配置文件
            Console.WriteLine($"list:Age={Configuration["list:Age"]} ");

控制器中读取

Asp.net框架默认添加了IConfiguration的依赖注入

 public class MoviesController : Controller
 {
     public IConfiguration Configuration { get; }
     public MoviesController(IConfiguration configuration)
     {
            Configuration = configuration;
     }
 }

对象读取

我们在appsettings.json 都添加一个 SiteConfig 节点。

 "SiteConfig": {
   "Name": "LineZero's Blog",
   "Info": "ASP.NET Core 开发及跨平台,配置文件读取"
 },

然后新建一个SiteConfig 类。

public class SiteConfig
{
    public string Name { get; set; }
    public string Info { get; set; }
}

首先在 ConfigureServices 中添加Options 及对应配置。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddOptions();       services.Configure<SiteConfig>(Configuration.GetSection("SiteConfig"));
}

然后我们在 Controller 中读取。

public class HomeController : Controller
{
    public SiteConfig Config;

    public HomeController(IOptions<SiteConfig> option)
    {
        Config = option.Value;
    }
    public IActionResult Index()
    {
        return View(Config);
    }
}

自定义配置文件

添加一个配置文件appSetting.Development.json并修改program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration(config => {
                config.AddJsonFile("appSetting.Development.json");
            }).UseStartup<Startup>();

多环境配置文件

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((context,config) => {
                config.AddJsonFile($"appSetting.{context.HostingEnvironment.EnvironmentName}.json");
            }).UseStartup<Startup>();

http://lihuaxi.xjx100.cn/news/58072.html

相关文章

2022-10-04 语法分析器bison说明

https://www.gnu.org/software/bison/manual/bison.html 参考: https://blog.csdn.net/weixin_44705391/article/details/115555161 https://zhuanlan.zhihu.com/p/52326306 https://zhuanlan.zhihu.com/p/120812270 https://zhuanlan.zhihu.com/p/89479111 说明: Unix Le…

【问题解决】大佬亲授的姿势——PlatformIO生成bin文件方法

微信关注公众号 “DLGG创客DIY”设为“星标”&#xff0c;重磅干货&#xff0c;第一时间送达。最近写创客项目程序基本都用PlatformIO&#xff08;以后简称PIO&#xff09;&#xff0c;PIO在很多方面都优于arduino IDE&#xff0c;今天就不展开了啊&#xff0c;回头专门起一篇文…

【蓝桥杯真题练习】STEMA科技素养练习题库 答案版004 持续更新中~

1、在一个圆形的桌子上,甲和乙轮流摆放硬币。规则是每次每人摆一个,硬币不能互相重叠, 也不能有一部分在桌面边缘之外。若轮到一方摆放硬币时找不到地方摆放,则另一方获胜。假如甲第一个摆放硬币,那么( ) A 甲必胜 B 乙必胜 C 会平局 D 条件不足无法判断 答案:A…

基于PHP的公共课考勤管理系统设计与实现

目录 第一章 概 述 5 第二章 系统的需求分析 10 2.1 系统需求分析 10 1&#xff0e;任务概述 10 2.功能需求 10 2.2 总体设计 11 1&#xff0e;本课题研究的内容 11 2&#xff0e;此系统共分为六个较大的模块&#xff1a; 11 表2 教师信息表&#xff08;t_infor&#xff09; 17…

分类算法学习(python)

数据集 调用方式&#xff1a;load_xxxx() 鸢尾花数据集150*4 load_iris() 手写数字load_digits() fetch_xxx() 路透社新闻语料数据集fetch_rev1() (较大的数据集) 实例&#xff1a; #各类信息与房价from sklearn.datasets import load_boston bostonload_boston() print(boston…

ViewModel的基本用法

本来想弄个游戏开始的倒计时&#xff0c;结果用普通方法没弄出来&#xff0c;后来发现需要用LifeCirle可以对页面进行实时更新。于是找了相关教材。 package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewMode…

手机运行慢怎么办

相信很多人在使用手机的时候都会遇到相同的问题手机卡顿&#xff01;而手机卡顿的原因也有很多&#xff0c;如安装了大量的软件应用&#xff0c;手机使用的年数时间太长&#xff0c;手机的配置以及电池老化&#xff0c;手机用久了之后就会产生一些系统垃圾&#xff0c;这些垃圾…

华为手机的衰退,再次让国产手机和三星都成为输家,只有苹果赢了

counterpoint公布二季度全球智能手机市场的利润份额数据&#xff0c;数据显示中国手机和三星占有的利润份额都下滑了&#xff0c;而苹果则取得了更多的利润份额&#xff0c;这显然出乎业界预料&#xff0c;为何华为手机的衰退却导致国产手机和三星都成为输家呢&#xff1f;coun…