前言
.net core 来势已不可阻挡. 既然挡不了, 那我们就顺应它. 了解它并学习它. 今天我们就来看看和之前. net 版本的配置文件读取方式有何异同, 这里不在赘述. NET Core 基础知识.
实现
注: 需要 NuGet 引入: Microsoft.Extensions.Options.ConfigurationExtensions
我们再配置文件 appsettings.json 中 新增自定义 API Json 如下:
- {
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "API": {
- "Url": "http://localhost:8080/",
- "getclub": "api/club"
- }
- }
然后我们定义一个静态类, 再类中申明一个 IConfigurationSection 类型变量
private static IConfigurationSection _appSection = null;
写一个 AppSetting 静态方法获取到配置的 Value 项, 代码如下:
- public static string AppSetting(string key)
- {
- string str = string.Empty;
- if (_appSection.GetSection(key) != null)
- {
- str = _appSection.GetSection(key).Value;
- }
- return str;
- }
需要设置 IConfigurationSection 初始值, 如下:
- public static void SetAppSetting(IConfigurationSection section)
- {
- _appSection = section;
- }
然后写一个根据不同 Json 项读取出对应的值即可:
- public static string GetSite(string apiName)
- {
- return AppSetting(apiName);
- }
有了以上几个步骤, 基本上读取代码已经全部写完, 剩下最后一个最重要的步骤, 将要读取的 Json 文件配置到 Startup.cs 的 Configure 方法中, 如下:
这样, 我们就可以很轻松的获取到我们想要的配置项了, 整段 CS 代码如下:
- /// <summary>
- /// 配置信息读取模型
- /// </summary>
- public static class SiteConfig
- {
- private static IConfigurationSection _appSection = null;
- /// <summary>
- /// API 域名地址
- /// </summary>
- public static string AppSetting(string key)
- {
- string str = string.Empty;
- if (_appSection.GetSection(key) != null)
- {
- str = _appSection.GetSection(key).Value;
- }
- return str;
- }
- public static void SetAppSetting(IConfigurationSection section)
- {
- _appSection = section;
- }
- public static string GetSite(string apiName)
- {
- return AppSetting(apiName);
- }
- }
最后 , 我们来跑一下演示效果如下:
来源: https://www.cnblogs.com/zhangxiaoyong/p/9411036.html