ASP.NET Core中的Configuration配置二

作者:暗断肠 时间:2024-06-05 09:33:11 

相关文章

ASP.NET Core2.2 中的Configuration配置一

ASP.NET Core2.2 中的Configuration配置二

1.内存配置

MemoryConfigurationProvider使用内存中集合作为配置键值对。若要激活内存中集合配置,请在ConfigurationBuilder的实例上调用AddInMemoryCollection扩展方法。可以使用IEnumerable<KeyValuePair<String,String>> 初始化配置提供程序。构建主机时调用ConfigureAppConfiguration以指定应用程序的配置:

public class Program
{
   public static readonly Dictionary<string, string> _dict =
       new Dictionary<string, string>
       {
           {"MemoryCollectionKey1", "value1"},
           {"MemoryCollectionKey2", "value2"}
       };
   public static void Main(string[] args)
   {
       CreateWebHostBuilder(args).Build().Run();
   }
   public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .ConfigureAppConfiguration((hostingContext, config) =>
           {
               config.AddInMemoryCollection(_dict);
           })
           .UseStartup<Startup>();
}

而通过启动应用程序时会看到如下配置信息:

ASP.NET Core中的Configuration配置二

1.1GetValue

ConfigurationBinder.GetValue<T>从具有指定键的配置中提取一个值,并可以将其转换为指定类型。如果未找到该键,则获取配置默认值。如上述示例中,配置两个value1、value2值,现在我们在键MemoryCollectionKey1配置中提取对应字符串值,如果找不到配置键MemoryCollectionKey1,则默认使用value3配置值,示例代码如下:

public Startup(IConfiguration configuration)
{
   Configuration = configuration;
   var config = Configuration.GetValue<string>("MemoryCollectionKey1", "value3");
}

而通过启动应用程序时会看到如下配置信息:

ASP.NET Core中的Configuration配置二

ConfigurationBinder.GetValue找到定义string类型MemoryCollectionKey1键值并输出。如果我们把获取键名称更改为MemoryCollectionKey3,再来看看获取键值输出结果:

ASP.NET Core中的Configuration配置二


我们会看到当ConfigurationBinder.GetValue找不到定义string类型MemoryCollectionKey3键时,则输出默认值。

2.绑定到实体类

可以使用选项模式将文件配置绑定到相关实体类。配置值作为字符串返回,但调用Bind 可以绑定POCO对象。Bind在Microsoft.Extensions.Configuration.Binder包中,后者在 Microsoft.AspNetCore.App元包中。现在我们在CoreWeb/Models目录下新增一个叫starship.json文件,配置内容如下:

{
 "starship": {
   "name": "USS Enterprise",
   "registry": "NCC-1701",
   "class": "Constitution",
   "length": 304.8,
   "commissioned": false
 },
 "trademark": "Paramount Pictures Corp. http://www.paramount.com"
}

然后再新增一个对应配置内容的实体模型(/Models/Starship.cs):

public class Starship
{
   public string Name { get; set; }
   public string Registry { get; set; }
   public string Class { get; set; }
   public decimal Length { get; set; }
   public bool Commissioned { get; set; }
}

构建主机时调用ConfigureAppConfiguration以指定应用程序的配置:

public static void Main(string[] args)
{
   CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
   WebHost.CreateDefaultBuilder(args)
       .ConfigureAppConfiguration((hostingContext, config) =>
       {
           config.SetBasePath(Directory.GetCurrentDirectory());
           config.AddJsonFile(
               "starship.json", optional: true, reloadOnChange: true);
       })
       .UseStartup<Startup>();

示例应用程序调用GetSection方法获取json文件中starship键。通过Bind方法把starship键属性值绑定到Starship类的实例中:

var starship = new Starship();
Configuration.GetSection("starship").Bind(starship);
var _starship = starship;

当应用程序启动时会提供JSON文件配置内容:

ASP.NET Core中的Configuration配置二

3.绑定至对象图

通过第2小节我们学习到如何绑定配置文件内容映射到实例化实体类属性去,同样,配置文件内容也可以绑定到对象图去。现在我们在CoreWeb/Models目录下新增一个叫tvshow.xml文件,配置内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
 <tvshow>
   <metadata>
     <series>Dr. Who</series>
     <title>The Sun Makers</title>
     <airdate>11/26/1977</airdate>
     <episodes>4</episodes>
   </metadata>
   <actors>
     <names>Tom Baker, Louise Jameson, John Leeson</names>
   </actors>
   <legal>(c)1977 BBC https://www.bbc.co.uk/programmes/b006q2x0</legal>
 </tvshow>
</configuration>

然后再新增一个对应配置内容的实体模型(/Models/TvShow.cs),其对象图包含Metadata和 Actors类:

public class TvShow
{
   public Metadata Metadata { get; set; }
   public Actors Actors { get; set; }
   public string Legal { get; set; }
}
public class Metadata
{
   public string Series { get; set; }
   public string Title { get; set; }
   public DateTime AirDate { get; set; }
   public int Episodes { get; set; }
}
public class Actors
{
   public string Names { get; set; }
}

构建主机时调用ConfigureAppConfiguration以指定应用程序的配置:
config.AddXmlFile("tvshow.xml", optional: true, reloadOnChange: true);
使用Bind方法将配置内容绑定到整个TvShow对象图。将绑定实例分配给用于呈现的属性:

public Startup(IConfiguration configuration)
{
   Configuration = configuration;
   var tvShow = new TvShow();
   Configuration.GetSection("tvshow").Bind(tvShow);
   var _tvShow = tvShow;
}

当应用程序启动时会提供XML文件配置内容:

ASP.NET Core中的Configuration配置二

还有一种Bind方法可以将配置内容绑定到整个TvShow对象图:

public Startup(IConfiguration configuration)
{
   Configuration = configuration;
   var _tvShow = Configuration.GetSection("tvshow").Get<TvShow>();
}

当应用程序启动时会提供XML文件配置内容:

ASP.NET Core中的Configuration配置二

4.将数组绑定至类

Bind方法也支持把配置内容键中的数组绑定到对象类去。公开数字键段(:0:、:1:、&hellip; :{n}:)的任何数组格式都能够与POCO类数组进行绑定。使用内存配置提供应用程序在示例中加载这些键和值:

public class Program
{
   public static Dictionary<string, string> arrayDict =
           new Dictionary<string, string>
           {
               {"array:entries:0", "value0"},
               {"array:entries:1", "value1"},
               {"array:entries:2", "value2"},
               {"array:entries:4", "value4"},
               {"array:entries:5", "value5"}
           };
   public static void Main(string[] args)
   {
       CreateWebHostBuilder(args).Build().Run();
   }
   public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .ConfigureAppConfiguration((hostingContext, config) =>
           {
               config.SetBasePath(Directory.GetCurrentDirectory());
               config.AddInMemoryCollection(arrayDict);
           })
           .UseStartup<Startup>();
}

因为配置绑定程序无法绑定null值,所以该数组跳过了索引#3的值。在示例应用程序中,POCO类可用于保存绑定的配置数据:

public class ArrayExample
{
   public string[] Entries { get; set; }
}

将配置数据绑定至对象:

public Startup(IConfiguration configuration)
{
   Configuration = configuration;
   var arrayExample = new ArrayExample();
   Configuration.GetSection("array").Bind(arrayExample);
   var _arrayExample = arrayExample;
}

还可以使用ConfigurationBinder.Get<T>语法,从而产生更精简的代码:

public Startup(IConfiguration configuration)
{
   Configuration = configuration;
   var _arrayExample = _config.GetSection("array").Get<ArrayExample>();
}

当应用程序启动时会提供内存配置内容:

ASP.NET Core中的Configuration配置二

5.在Razor Pages页或MVC视图中访问配置

若要访问RazorPages页或MVC视图中的配置设置,请为Microsoft.Extensions.Configuration命名空间添加using指令(C#参考:using指令)并将IConfiguration注入页面或视图。
在Razor页面页中:

@page
@model IndexModel
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<!DOCTYPE html>
<html lang="en">
<head>
   <title>Index Page</title>
</head>
<body>
   <h1>Access configuration in a Razor Pages page</h1>
   <p>Configuration value for 'key': @Configuration["key"]</p>
</body>
</html>

在MVC视图中:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<!DOCTYPE html>
<html lang="en">
<head>
   <title>Index View</title>
</head>
<body>
   <h1>Access configuration in an MVC view</h1>
   <p>Configuration value for 'key': @Configuration["key"]</p>
</body>
</html>

来源:https://www.cnblogs.com/wzk153/p/11264554.html

标签:ASP.NET Core,Configuration,配置
0
投稿

猜你喜欢

  • 使用Python实现Wake On Lan远程开机功能

    2023-07-26 21:44:06
  • Django在pycharm下修改默认启动端口的方法

    2023-09-27 09:04:07
  • 深入了解NumPy 高级索引

    2023-07-02 05:22:51
  • python代码实现五子棋游戏

    2021-04-18 01:20:48
  • CentOS 7 中以命令行方式安装 MySQL 5.7.11 for Linux Generic 二进制版本教程详解

    2024-01-26 00:24:39
  • 什么样的分页案例才是好的

    2007-11-23 19:08:00
  • em与px的区别以及em特点和应用

    2008-11-11 12:03:00
  • Python Django view 两种return的实现方式

    2022-05-03 16:07:04
  • go使用consul实现服务发现及配置共享实现详解

    2024-04-23 09:48:01
  • 通过视图修改数据时所应掌握的基本准则

    2009-01-07 14:22:00
  • MySL实现如等级成色等特殊顺序的排序详解

    2024-01-17 15:11:07
  • 给验证码增加干扰的杂点

    2008-05-16 11:34:00
  • python 如何做一个识别率百分百的OCR

    2023-08-12 15:16:18
  • PHP连接和操作MySQL数据库基础教程

    2023-11-20 22:41:47
  • Python变量定义的简单使用介绍

    2021-08-23 07:35:26
  • mysql insert if not exists防止插入重复记录的方法

    2024-01-17 08:40:43
  • sqlserver 临时表 Vs 表变量 详细介绍

    2011-11-03 17:34:10
  • vue项目中使用axios遇到的相对路径和绝对路径问题

    2024-05-13 09:37:40
  • 基于fastapi框架的异步解读

    2022-12-19 21:45:24
  • 详解pandas.DataFrame.plot() 画图函数

    2021-06-02 21:41:49
  • asp之家 网络编程 m.aspxhome.com