欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ServiceStack NetCoreAppSettings 配置文件读取和设置

程序员文章站 2023-04-06 14:54:51
假设Node和npm已经安装 npm install -g @servicestack/cli 执行命令dotnet-new selfhost SSHost 这样就创建了ServiceStack的控制台程序,用VS2017解决方案,添加如下代码 项目SSHost里添加配置文件appsettings. ......

假设node和npm已经安装

npm install -g @servicestack/cli

执行命令dotnet-new selfhost sshost

这样就创建了servicestack的控制台程序,用vs2017解决方案,添加如下代码

 

using funq;
using microsoft.aspnetcore.builder;
using microsoft.aspnetcore.hosting;
using microsoft.extensions.configuration;
using microsoft.extensions.dependencyinjection;
using servicestack;
using sshost.serviceinterface;
using system;
using system.io;
using system.threading.tasks;

namespace sshost
{
    public class program
    {
        public static void main(string[] args)
        {
            var host = new webhostbuilder()
                .usekestrel()
                .usecontentroot(directory.getcurrentdirectory())
                .usestartup<startup>()
                .useurls(environment.getenvironmentvariable("aspnetcore_urls") ?? "http://localhost:5000/")
                .build();

            host.run();
        }
    }

    public class startup
    {

        public iconfiguration configuration { get; set; }
        public startup(iconfiguration configuration) => configuration = configuration;

        // this method gets called by the runtime. use this method to add services to the container.
        public void configureservices(iservicecollection services)
        {

        }

        // this method gets called by the runtime. use this method to configure the http request pipeline.
        public void configure(iapplicationbuilder app, ihostingenvironment env)
        {
            //nuget里添加microsoft.extensions.configuration.json,否则编译不认识addjsonfile
            var builder = new configurationbuilder()
                  .setbasepath(env.contentrootpath)
                  .addjsonfile($"appsettings.json", optional: true)
                  .addenvironmentvariables();

            configuration = builder.build();

            app.useservicestack(new apphost
            {
                appsettings = new netcoreappsettings(configuration)
            });

            app.run(context =>
            {
                context.response.redirect("/metadata");
                return task.fromresult(0);
            });
        }
    }

    public class apphost : apphostbase
    {
        public apphost()
            : base("sshost", typeof(myservices).assembly) { }

        public class pageconfig
        {
            public int lightlistpagesize { get; set; }

            public int gatewaylistpagesize { get; set; }
        }

        public override void configure(container container)
        {
            setconfig(new hostconfig
            {
                debugmode = appsettings.get(nameof(hostconfig.debugmode), false)
            });

            #region 读取或者设置netcoreappsettings

            //读取单个值
            console.writeline($"maxrecords: {appsettings.getstring("maxrecords")}");

            //读取对象属性
            console.writeline($"pageconfig: {appsettings.getstring("pageconfig:lightlistpagesize")}");

            //读取整个对象
            var pageconfig = appsettings.get<pageconfig>("pageconfig");

            console.writeline($"connectionstring: {appsettings.getstring("connectionstrings:defaultconnection")}");

            //设置每页记录最大数量为200
            appsettings.set<int>("maxrecords", 200);
            console.writeline($"maxrecords: {appsettings.getstring("maxrecords")}");

            pageconfig.lightlistpagesize = 50;
            pageconfig.gatewaylistpagesize = 60;

            //设置属性,然后读取对象
            appsettings.set<int>("pageconfig:lightlistpagesize", 50);
            var pageconfig2 = appsettings.get<pageconfig>("pageconfig");

            console.writeline("设置配置完毕");

            #endregion

        }
    }
}

 项目sshost里添加配置文件appsettings.json,里面配置内容如下

{
  "maxrecords": "300",
  "pageconfig": {
    "lightlistpagesize": "10",
    "gatewaylistpagesize": "20"
  },
  "connectionstrings": {
    "defaultconnection": "server=(localdb)\\mssqllocaldb;database=_change_me;trusted_connection=true;multipleactiveresultsets=true"
  }
}

编译运行,出现如下错误信息

1>------ 已启动全部重新生成: 项目: sshost.servicemodel, 配置: debug any cpu ------
1>sshost.servicemodel -> d:\sshost\sshost.servicemodel\bin\debug\netstandard2.0\sshost.servicemodel.dll
2>------ 已启动全部重新生成: 项目: sshost.serviceinterface, 配置: debug any cpu ------
2>sshost.serviceinterface -> d:\sshost\sshost.serviceinterface\bin\debug\netstandard2.0\sshost.serviceinterface.dll
3>------ 已启动全部重新生成: 项目: sshost, 配置: debug any cpu ------
4>------ 已启动全部重新生成: 项目: sshost.tests, 配置: debug any cpu ------
4>sshost.tests -> d:\sshost\sshost.tests\bin\debug\netcoreapp2.1\sshost.tests.dll
3>program.cs(47,20,47,31): error cs1061: “iconfigurationbuilder”未包含“addjsonfile”的定义,并且找不到可接受第一个“iconfigurationbuilder”类型参数的可访问扩展方法“addjsonfile”(是否缺少 using 指令或程序集引用?)
3>已完成生成项目“sshost.csproj”的操作 - 失败。
========== 全部重新生成: 成功 3 个,失败 1 个,跳过 0 个 ==========

nuget里添加microsoft.extensions.configuration.json,否则编译不认识addjsonfile

再次编译运行

ServiceStack NetCoreAppSettings 配置文件读取和设置

 

总结一下,servicestack的appsettings功能非常强大,并且非常好用,不仅支持过去的web.config,也支持.net core的appsettings.json,还支持文本文件

想了解更多的情况,可以查看文档:https://github.com/servicestack/docs/blob/master/docs/_documentation/appsettings.md