问题引出

asp.net core 默认将 web.config移除了,将配置文件统一放在了 xxx.json 格式的文件中。

有web.config时,我们需要读到配置文件时,一般是这样的:

var value1= configurationmanager.connectionstrings[“connstr”].connectionstring;

这个configurationmanager是在system.configuration 命名空间下的。

很不幸,默认情况下这个方法也不能用了。

 

如果在controller需要读取配置文件,在startup.cs文件中注册相关服务,可以类似于注册context一样:

// 1、注册相关服务,类似于如下的xxxcontext的例子

services.adddbcontext<xxxcontext>(xxx 。。。

 

// 2、controller读取

然后在具体controller的构造函数中作为参数获取。

类似于:

private iconfiguration _configuration;

public xxxcontroller(iconfiguration configuration)

{
    _configuration = configuration;
}

 

具体实现方式已有多篇文章讲解,请自行搜索,不再赘述。

这种方式引出两个问题:

1、多数controller是需要读取context的,但不是每个controller都需要读取配置文件,这种方式不够简洁

2、如果我们需要在controller之外的其他类文件中读取呢?

 

我们仿照configurationmanager读取web.config中文件的方式,自定义一个myconfigurationmanager 类。

我直接在上一篇文章中的示例程序添加演示。

 

详细步骤

步骤一:准备好素材,appsettings.json添加配置项

  “grandparent_key”: { “parent_key”: { “child_key”: “value1” } },

  “parent_key”: { “child_key”: “value2” },

  “child_key”: “value3”

 

 

步骤二:添加 myconfigurationmanager.cs

 

 

    /// <summary>

    /// 获取自定义的 json 配置文件

    /// </summary>

    static class myconfigurationmanager

    {

        public static iconfiguration appsetting { get; }

 

        static myconfigurationmanager()

        {

            // 注意:2.2版本的这个路径不对 会输出 xxx/iis express...类似这种路径,

            // 等3.0再看有没其他变化

            string directory = directory.getcurrentdirectory();

            appsetting = new configurationbuilder()

                     .setbasepath(directory)

                     .addjsonfile("myappsettings.json")

                     .build();

        }

    }

 

 

步骤三:调用

我们去homecontroller中添加一个测试方法

public iactionresult configtest()

{

            string value1 = myconfigurationmanager.appsetting["grandparent_key:parent_key:child_key"];

            string value2 = myconfigurationmanager.appsetting["parent_key:child_key"];

            string value3 = myconfigurationmanager.appsetting["child_key"];

            return view();

}

 

加个断点调试一下,可以看到输出了想要的结果。

 

总结

通过自定义的configuration方法可以方便读取json文件。

获取配置文件路径时,appcontext.basedirectory在 .net core 2.2和2.1不一样,

如果事先用的2.2模板,需要右键项目,将target framework设为2.1

 

 

p.s. 路径获取这块给出一个通用的方法,这样2.1和2.2就都满足了,如下:

var filename = "appsettings.json";

 

var directory = appcontext.basedirectory;

directory = directory.replace("\\", "/");

 

var filepath = $"{directory}/{filename}";

if (!file.exists(filepath))

{

    var length = directory.indexof("/bin");

    filepath = $"{directory.substring(0, length)}/{filename}";

}

 

 

祝 学习进步 :)

 

p.s. 系列文章列表: