您现在的位置是:群英 > 开发技术 > web开发
.NET CORE的配置文件只能用xml格式吗
Admin发表于 2022-06-01 17:31:05750 次浏览
相信很多人对“.NET CORE的配置文件只能用xml格式吗,json格式才是推荐的方法”都不太了解,下面群英小编为你详细解释一下这个问题,希望对你有一定的帮助

在.net framework中,配置文件一般采用的是xml格式的,.net framework提供了专门的configurationmanager来读取配置文件的内容,.net core中推荐使用json格式的配置文件,那么在.net core中该如何读取json文件呢?

一、在startup类中读取json配置文件

1、使用configuration直接读取

看下面的代码:

public iconfiguration configuration { get; }

configuration属性就是.net core中提供的用来读取json文件。例如:

public void configure(iapplicationbuilder app, ihostingenvironment env)
{

            string option1 = $"option1 = {this.configuration["option1"]}";
            string option2 = $"option2 = {this.configuration["option2"]}";
            string suboption1 = $"suboption1 = {this.configuration["subsection:suboption1"]}";
            // 读取数组
            string name1 = $"name={this.configuration["student:0:name"]} ";
            string age1 = $"age= {this.configuration["student:0:age"]}";
            string name2 = $"name={this.configuration["student:1:name"]}";
            string age2 = $"age= {this.configuration["student:1:age"]}";
            // 输出
            app.run(c => c.response.writeasync(option1+"\r\n"+option2+ "\r\n"+suboption1+ "\r\n"+name1+ "\r\n"+age1+ "\r\n"+name2+ "\r\n"+age2));
            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
            }
            else
            {
                app.usehsts();
            }

            app.usehttpsredirection();
            app.usemvc();
}

结果:

2、使用ioptions接口

1、定义实体类

public class mongodbhostoptions
{
        ////// 连接字符串
        ///public string connection { get; set; }
        ////// 库
        ///public string database { get; set; }

        public string table { get; set; }
}

2、修改json文件

在appsettings.json文件中添加mongodbhost节点:

{
  "logging": {
    "loglevel": {
      "default": "warning"
    }
  },
  "option1": "value1_from_json",
  "option2": 2,
  "subsection": {
    "suboption1": "subvalue1_from_json"
  },
  "student": [
    {
      "name": "gandalf",
      "age": "1000"
    },
    {
      "name": "harry",
      "age": "17"
    }
  ],
  "allowedhosts": "*",
  //mongodb
  "mongodbhost": {
    "connection": "mongodb://127.0.0.1:27017",
    "database": "templatedb",
    "table": "cdatemplateinfo"
  }
}

注意:

mongodbhost里面的属性名必须要和定义的实体类里面的属性名称一致。

3、在startup类里面配置

添加optionconfigure方法绑定

private void optionconfigure(iservicecollection services)
{
      //mongodbhost信息
      services.configure(configuration.getsection("mongodbhost"));
}

在configureservices方法中调用上面定义的方法:

public void configureservices(iservicecollection services)
{
     // 调用optionconfigure方法
     optionconfigure(services);           
     services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);
}

在控制器中使用,代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.http;
using microsoft.aspnetcore.mvc;
using microsoft.extensions.options;

namespace readjsondemo.controllers
{
    [route("api/[controller]")]
    [apicontroller]
    public class mongodbcontroller : controllerbase
    {
        private readonly mongodbhostoptions _mongodbhostoptions;

        ////// 通过构造函数注入
        //////public mongodbcontroller(ioptionsmongodbhostoptions)
        {
            _mongodbhostoptions = mongodbhostoptions.value;
        }

        [httpget]
        public async task get()
        {
           await response.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndatabase;" + _mongodbhostoptions.database + "\r\ntable:" + _mongodbhostoptions.table);
        }
    }
}

运行结果:

3、读取自定义json文件

在上面的例子中都是读取的系统自带的appsettings.json文件,那么该如何读取我们自己定义的json文件呢?这里可以使用configurationbuilder类。

实例化类

var builder = new configurationbuilder();

 添加方式1

builder.addjsonfile("path", false, true);

 其中path表示json文件的路径,包括路径和文件名。

添加方式2

builder.add(new jsonconfigurationsource {path= "custom.json",optional=false,reloadonchange=true }).build()

具体代码如下:

private void customoptionconfigure(iservicecollection services)
{
            iconfiguration _configuration;
            var builder = new configurationbuilder();
            // 方式1
            //_configuration = builder.addjsonfile("custom.json", false, true).build();
            // 方式2
            _configuration = builder.add(new jsonconfigurationsource {path= "custom.json",optional=false,reloadonchange=true }).build();
            services.configure(_configuration.getsection("websiteconfig"));
}

configureservices方法如下:

public void configureservices(iservicecollection services)
{
            // 调用optionconfigure方法
            optionconfigure(services);
            customoptionconfigure(services);
            services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);
}

控制器代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.http;
using microsoft.aspnetcore.mvc;
using microsoft.extensions.options;

namespace readjsondemo.controllers
{
    [route("api/[controller]")]
    [apicontroller]
    public class mongodbcontroller : controllerbase
    {
        private readonly mongodbhostoptions _mongodbhostoptions;

        private readonly websiteoptions _websiteoptions;

        ////// 通过构造函数注入
        //////public mongodbcontroller(ioptionsmongodbhostoptions,ioptionswebsiteoptions)
        {
            _mongodbhostoptions = mongodbhostoptions.value;
            _websiteoptions = websiteoptions.value;
        }

        [httpget]
        public async task get()
        {
           await response.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndatabase;" + _mongodbhostoptions.database + "\r\ntable:" + _mongodbhostoptions.table);
            await response.writeasync("\r\n");
            await response.writeasync("websitename:" + _websiteoptions.websitename + "\r\nwebsiteurl;" + _websiteoptions.websiteurl);
        }
    }
}

二、在类库中读取json文件

在上面的示例中都是直接在应用程序中读取的,那么如何在单独的类库中读取json文件呢?看下面的示例代码:

using microsoft.extensions.configuration;
using microsoft.extensions.dependencyinjection;
using microsoft.extensions.options;
using system;
using system.collections.generic;
using system.io;
using system.text;

namespace common
{
    public class jsonconfighelper
    {
        public static t getappsettings(string filename, string key) where t : class, new()
        {
            // 获取bin目录路径
            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}";
            }

            iconfiguration configuration;
            var builder = new configurationbuilder();
            
            builder.addjsonfile(filepath, false, true);
            configuration = builder.build();

            var appconfig = new servicecollection()
                .addoptions()
                .configure(configuration.getsection(key))
                .buildserviceprovider()
                .getservice()
                .value;

            return appconfig;
        }
    }
}

注意:这里要添加如下几个程序集,并且要注意添加的程序集的版本要和.net core web项目里面的程序集版本一致,否则会报版本冲突的错误

  • 1、microsoft.extensions.configuration
  • 2、microsoft.extensions.configuration.json
  • 3、microsoft.extensions.options
  • 4、microsoft.extensions.options.configurationextensions
  • 5、microsoft.extensions.options

json文件如下:

{
  "websiteconfig": {
    "websitename": "customwebsite",
    "websiteurl": "https:localhost:12345"
  },
  "dbconfig": {
    "datasource": "127.0.0.1",
    "initialcatalog": "mydb",
    "userid": "sa",
    "password": "123456"
  }
}

dbhostoptions实体类定义如下:

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;

namespace readjsondemo
{
    public class dbhostoptions
    {
        public string datasource { get; set; }

        public string initialcatalog { get; set; }

        public string userid { get; set; }

        public string password { get; set; }
    }
}

注意:这里的dbhostoptions实体类应该建在单独的类库中,这里为了演示方便直接建在应用程序中了。

在控制器中调用:

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using common;
using microsoft.aspnetcore.http;
using microsoft.aspnetcore.mvc;
using microsoft.extensions.options;

namespace readjsondemo.controllers
{
    [route("api/[controller]")]
    [apicontroller]
    public class mongodbcontroller : controllerbase
    {
        private readonly mongodbhostoptions _mongodbhostoptions;

        private readonly websiteoptions _websiteoptions;

        ////// 通过构造函数注入
        //////public mongodbcontroller(ioptionsmongodbhostoptions,ioptionswebsiteoptions)
        {
            _mongodbhostoptions = mongodbhostoptions.value;
            _websiteoptions = websiteoptions.value;
        }

        [httpget]
        public async task get()
        {
            dbhostoptions dboptions = jsonconfighelper.getappsettings("custom.json", "dbconfig");
            await response.writeasync("datasource:" + dboptions.datasource + "\r\ninitialcatalog;" + dboptions.initialcatalog+ "\r\nuserid:"+dboptions.userid+ "\r\npassword"+dboptions.password);
            await response.writeasync("\r\n");
            await response.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndatabase;" + _mongodbhostoptions.database + "\r\ntable:" + _mongodbhostoptions.table);
            await response.writeasync("\r\n");
            await response.writeasync("websitename:" + _websiteoptions.websitename + "\r\nwebsiteurl;" + _websiteoptions.websiteurl);           
        }
    }
}

运行结果:



以上就是关于“.NET CORE的配置文件只能用xml格式吗,json格式才是推荐的方法”的相关知识,感谢各位的阅读,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注群英网络,小编每天都会为大家更新不同的知识。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

相关信息推荐
2021-11-05 17:25:05 
摘要:这篇文章给大家分享的是PHP反射的内容,主要带大家来回顾一下PHP中反射的基础知识,对新手学习PHP中反射也有一定的帮助,那么感兴趣的朋友接下来跟随小编一起学习一下吧。
2022-05-17 11:47:20 
摘要:android 倒计时一般实现方式:handler+postdelayed() 方式timer + timertask + handler 方式scheduledexecutorservice + h
2022-05-20 17:11:42 
摘要:下面由golang​教程栏目给大家介绍cat输出乱码问题解决方法,希望对需要的朋友有所帮助!
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部