iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > ASP.NET >ASP.NET Core中的Configuration配置二
  • 285
分享到

ASP.NET Core中的Configuration配置二

2024-04-02 19:04:59 285人浏览 薄情痞子
摘要

目录1.内存配置1.1GetValue2.绑定到实体类3.绑定至对象图4.将数组绑定至类5.在Razor Pages页或mvc视图中访问配置相关文章 ASP.net core2.2

相关文章

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>();
}

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

1.1GetValue

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

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

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

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


我们会看到当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文件配置内容:

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文件配置内容:

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

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

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

4.将数组绑定至类

Bind方法也支持把配置内容键中的数组绑定到对象类去。公开数字键段(:0:、:1:、… :{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>();
}

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

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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: ASP.NET Core中的Configuration配置二

本文链接: https://www.lsjlt.com/news/145194.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • ASP.NET Core中的Configuration配置二
    目录1.内存配置1.1GetValue2.绑定到实体类3.绑定至对象图4.将数组绑定至类5.在Razor Pages页或MVC视图中访问配置相关文章 ASP.NET Core2.2 ...
    99+
    2024-04-02
  • ASP.NET Core中的Configuration配置一
    目录1.前言2.命令行配置3.文件配置3.1 INI配置3.2 JSON配置3.2.1GetSection、GetChildren和Exists3.3 XML配置相关文章 ASP.N...
    99+
    2024-04-02
  • ASP.NET Core中的Configuration如何配置
    这篇文章主要讲解了“ASP.NET Core中的Configuration如何配置”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“ASP.NET Core中的Configu...
    99+
    2023-06-29
  • ASP.NET Core中的Configuration怎么配置
    这篇文章主要讲解了“ASP.NET Core中的Configuration怎么配置”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“ASP.NET Core中的Configu...
    99+
    2023-06-29
  • ASP.NET Core配置设置之Configuration包
    ASP.NET Core 中提供了一个Configuration 包,用以应用配置基于配置提供程序建立的键值对。这里以json文件配置的方式,简单的介绍一下它的用法。 首先...
    99+
    2024-04-02
  • ASP.NET Core中的配置有哪些
    这篇文章主要讲解了“ASP.NET Core中的配置有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“ASP.NET Core中的配置有哪些”吧!背景AS...
    99+
    2024-04-02
  • .Net Core配置Configuration具体实现
    目录核心类 构建ConfigurationBuilder IConfigurationSource ConfigurationProvider ConfigurationRoot 查...
    99+
    2024-04-02
  • ASP.NET Core中的环境怎么配置
    这篇文章主要介绍了ASP.NET Core中的环境怎么配置的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇ASP.NET Core中的环境怎么配置文章都会有所收获,下面我们一起来看看吧。1.环...
    99+
    2023-06-29
  • 如何在ASP.NET Core 的任意类中注入Configuration
    目录遇到的问题解决方案总结遇到的问题 我已经通读了 MSDN 上关于 Configuration 的相关内容,文档说可实现在 application 的任意位置访问 Configur...
    99+
    2024-04-02
  • ASP.NET Core中的SSL证书如何配置
    在ASP.NET Core中配置SSL证书可以通过以下步骤进行: 生成SSL证书:可以使用工具如OpenSSL或者通过一些在线服...
    99+
    2024-05-09
    ASP.NET SSL证书
  • ASP.Net Core MVC中获取配置信息
    这篇文章主要为大家展示了“ASP.Net Core MVC中获取配置信息”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“ASP.Net Core MVC中获...
    99+
    2023-06-29
  • ASP.NET Core中的Options选项模式怎么配置
    这篇文章主要介绍“ASP.NET Core中的Options选项模式怎么配置”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“ASP.NET Core中的Options选项模式怎么配...
    99+
    2023-06-29
  • ASP.NET Core通用主机的系统配置
    ASP.NET Core 2.0 中的 WebHost(实现 IWebHost 的基类)是用于为进程提供 HTTP 服务器功能的基础结构项目,例如,如果...
    99+
    2024-04-02
  • ASP.NET Core开发环境安装配置
    ASP.NET Core环境设置 1.如何设置用于.NetCore应用程序开发的开发机器2.安装SDK和IDE3.验证安装 开发和.NET Core应用程序所需的工具和软件 1.设备...
    99+
    2024-04-02
  • 如何使用ASP.NET Core 配置文件
    目录前言Json配置文件的使用RedisHelper类XML配置文件的使用前言 在ASP.NET ,我们使用XML格式的.Config文件来作为配置文件,而在ASP.NET Core...
    99+
    2024-04-02
  • ASP.NET Core配置系统实例分析
    本文小编为大家详细介绍“ASP.NET Core配置系统实例分析”,内容详细,步骤清晰,细节处理妥当,希望这篇“ASP.NET Core配置系统实例分析”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知...
    99+
    2023-07-05
  • ASP.NET Core配置和管理Web主机
    目录1.前言2.设置主机2.1执行下列任务2.2重写和增强定义的配置3.主机配置值3.1应用程序键(名称)3.2捕获启动错误3.3内容根3.4详细错误3.5环境3.6HTTPS端口3...
    99+
    2024-04-02
  • SpringBoot中的配置类(@Configuration)
    目录SpringBoot基于java类的配置第一步第二步第三步第四步测试SpringBoot自定义配置类1.方式一2.方式二SpringBoot基于java类的配置 java配置主要...
    99+
    2024-04-02
  • Asp.Net Core配置多环境log4net配置文件的全过程
    目录前言配置log4net总结前言 在之前的文章中有讲到AspNetCore多环境配置文件的应用,我们根据自己多种环境分别配置多个appsettings.$EnvironmentNa...
    99+
    2024-04-02
  • ASP.NET Core中MVC模式实现路由二
    目录1.URL生成2.URL生成方式2.1根据操作名称生成URL2.2根据路由生成URL2.3在HTML中生成URL2.4在操作结果中生成URL3.区域(Area)4.实现IActi...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作