【.NetCore】读取appsetting.json中的配置参数

前言

方法很多,下面的例子也是从百度上搜索到的,原文链接已经找不到了。

方法1

1.添加NovelSetting节点,写入相关的配置信息

 

 2.创建类,字段与上面的配置一致

 

 3.StartUp.cs中获取

添加读取的方法,将配置信息写入到对应的参数类中

 

 4.使用

在控制器中,如下设置,即可。

 

方法2

1.在appsetting.json中创建节点,保存相关的配置

 

 2.创建操作类

using Microsoft.Extensions.Configuration;

namespace NoteServer.Core
{
    /// <summary>
    /// 配置信息
    /// </summary>
    public class AppSettings
    {
        private static IConfigurationSection appSection = null;
        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetAppSeting(string key)
        {
            if (appSection.GetSection(key) != null)
            {
                return appSection.GetSection(key).Value;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 设置配置文件
        /// </summary>
        /// <param name="section"></param>
        public static void SetAppSetting(IConfigurationSection section)
        {
            appSection = section;
        }
    }
}

 

 3.在StartUp.cs中获取

 

 4.使用

 

posted @ 2020-06-02 14:19  我有我奥妙  阅读(2304)  评论(0编辑  收藏  举报