假设Node和npm已经安装

npm install -g @servicestack/cli

执行命令dotnet-new selfhost SSHost

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

  1. using Funq;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Hosting;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using ServiceStack;
  7. using SSHost.ServiceInterface;
  8. using System;
  9. using System.IO;
  10. using System.Threading.Tasks;
  11.  
  12. namespace SSHost
  13. {
  14. public class Program
  15. {
  16. public static void Main(string[] args)
  17. {
  18. var host = new WebHostBuilder()
  19. .UseKestrel()
  20. .UseContentRoot(Directory.GetCurrentDirectory())
  21. .UseStartup<Startup>()
  22. .UseUrls(Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://localhost:5000/")
  23. .Build();
  24.  
  25. host.Run();
  26. }
  27. }
  28.  
  29. public class Startup
  30. {
  31.  
  32. public IConfiguration Configuration { get; set; }
  33. public Startup(IConfiguration configuration) => Configuration = configuration;
  34.  
  35. // This method gets called by the runtime. Use this method to add services to the container.
  36. public void ConfigureServices(IServiceCollection services)
  37. {
  38.  
  39. }
  40.  
  41. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  42. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  43. {
  44. //nuget里添加Microsoft.Extensions.Configuration.json,否则编译不认识AddJsonFile
  45. var builder = new ConfigurationBuilder()
  46. .SetBasePath(env.ContentRootPath)
  47. .AddJsonFile($"appsettings.json", optional: true)
  48. .AddEnvironmentVariables();
  49.  
  50. Configuration = builder.Build();
  51.  
  52. app.UseServiceStack(new AppHost
  53. {
  54. AppSettings = new NetCoreAppSettings(Configuration)
  55. });
  56.  
  57. app.Run(context =>
  58. {
  59. context.Response.Redirect("/metadata");
  60. return Task.FromResult();
  61. });
  62. }
  63. }
  64.  
  65. public class AppHost : AppHostBase
  66. {
  67. public AppHost()
  68. : base("SSHost", typeof(MyServices).Assembly) { }
  69.  
  70. public class PageConfig
  71. {
  72. public int LightListPageSize { get; set; }
  73.  
  74. public int GatewayListPageSize { get; set; }
  75. }
  76.  
  77. public override void Configure(Container container)
  78. {
  79. SetConfig(new HostConfig
  80. {
  81. DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
  82. });
  83.  
  84. #region 读取或者设置NetCoreAppSettings
  85.  
  86. //读取单个值
  87. Console.WriteLine($"MaxRecords: {AppSettings.GetString("MaxRecords")}");
  88.  
  89. //读取对象属性
  90. Console.WriteLine($"PageConfig: {AppSettings.GetString("PageConfig:LightListPageSize")}");
  91.  
  92. //读取整个对象
  93. var pageConfig = AppSettings.Get<PageConfig>("PageConfig");
  94.  
  95. Console.WriteLine($"ConnectionString: {AppSettings.GetString("ConnectionStrings:DefaultConnection")}");
  96.  
  97. //设置每页记录最大数量为200
  98. AppSettings.Set<int>("MaxRecords", );
  99. Console.WriteLine($"MaxRecords: {AppSettings.GetString("MaxRecords")}");
  100.  
  101. pageConfig.LightListPageSize = ;
  102. pageConfig.GatewayListPageSize = ;
  103.  
  104. //设置属性,然后读取对象
  105. AppSettings.Set<int>("PageConfig:LightListPageSize", );
  106. var pageConfig2 = AppSettings.Get<PageConfig>("PageConfig");
  107.  
  108. Console.WriteLine("设置配置完毕");
  109.  
  110. #endregion
  111.  
  112. }
  113. }
  114. }

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

  1. {
  2. "MaxRecords": "",
  3. "PageConfig": {
  4. "LightListPageSize": "",
  5. "GatewayListPageSize": ""
  6. },
  7. "ConnectionStrings": {
  8. "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  9. }
  10. }

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

  1. >------ 已启动全部重新生成: 项目: SSHost.ServiceModel, 配置: Debug Any CPU ------
  2. >SSHost.ServiceModel -> D:\SSHost\SSHost.ServiceModel\bin\Debug\netstandard2.\SSHost.ServiceModel.dll
  3. >------ 已启动全部重新生成: 项目: SSHost.ServiceInterface, 配置: Debug Any CPU ------
  4. >SSHost.ServiceInterface -> D:\SSHost\SSHost.ServiceInterface\bin\Debug\netstandard2.\SSHost.ServiceInterface.dll
  5. >------ 已启动全部重新生成: 项目: SSHost, 配置: Debug Any CPU ------
  6. >------ 已启动全部重新生成: 项目: SSHost.Tests, 配置: Debug Any CPU ------
  7. >SSHost.Tests -> D:\SSHost\SSHost.Tests\bin\Debug\netcoreapp2.\SSHost.Tests.dll
  8. >Program.cs(,,,): error CS1061: IConfigurationBuilder”未包含“AddJsonFile”的定义,并且找不到可接受第一个“IConfigurationBuilder”类型参数的可访问扩展方法“AddJsonFile”(是否缺少 using 指令或程序集引用?)
  9. >已完成生成项目“SSHost.csproj”的操作 - 失败。
  10. ========== 全部重新生成: 成功 个,失败 个,跳过 ==========

nuget里添加Microsoft.Extensions.Configuration.json,否则编译不认识AddJsonFile

再次编译运行

总结一下,ServiceStack的AppSettings功能非常强大,并且非常好用,不仅支持过去的Web.config,也支持.Net Core的appsettings.json,还支持文本文件

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

ServiceStack NetCoreAppSettings 配置文件读取和设置的更多相关文章

  1. [spring源码学习]二、IOC源码——配置文件读取

    一.环境准备 对于学习源码来讲,拿到一大堆的代码,脑袋里肯定是嗡嗡的,所以从代码实例进行跟踪调试未尝不是一种好的办法,此处,我们准备了一个小例子: package com.zjl; public cl ...

  2. VS2012中,C# 配置文件读取 + C#多个工程共享共有变量 + 整理using语句

    (一) C# 配置文件读取 C#工程可以自动生成配置文件,以便整个工程可以使用设置的配置进行后续的处理工作. 1. 首先,右键工程文件-->Properties -->settings-- ...

  3. C# 配置文件读取与修改(转)

    C# 配置文件读取与修改   配置文件在很多情况下都使用到, 配置文件分为两种 一种是应用程序的配置文件, 一种是web的配置文件. 两种配置文件最大的区别是web的配置文件更新之后会实时更新, 应用 ...

  4. smarty 从配置文件读取变量

    smarty变量分3种: Variables [变量] Variables assigned from PHP [从PHP分配的变量] Variables loaded from config fil ...

  5. 【Spring源码分析】配置文件读取流程

    前言 Spring配置文件读取流程本来是和http://www.cnblogs.com/xrq730/p/6285358.html一文放在一起的,这两天在看Spring自定义标签的时候,感觉对Spri ...

  6. MySql5.7配置文件my.cnf设置

    # MySql5.7配置文件my.cnf设置[client]port = 3306socket = /tmp/mysql.sock [mysqld]########################## ...

  7. Python模块之: ConfigParser 配置文件读取

    Python模块之: ConfigParser 配置文件读取   ConfigParser用于读写类似INI文件的配置文件,配置文件的内容可组织为组,还支持多个选项值(option-value)类型. ...

  8. MySql5.7配置文件my.ini 设置 my.ini文件路径

    mysql配置文件my-default.ini  my.ini修改后重启无效,原来是路径错了,记录一下: windows操作系统下: 1. 由于我们使用MySql 时,需要修改mysql 的 my.i ...

  9. MySql5.7 配置文件 my.cnf 设置

    https://blog.csdn.net/gzt19881123/article/details/52594783 # MySql5.7配置文件my.cnf设置 [client] port = 33 ...

随机推荐

  1. Metasploit学习

    阶段一:初步渗透 GO! msfconsole 相关漏洞 msf > search platform: windows xp sp3 查看某个漏洞后,查看漏洞详细信息 msf > info ...

  2. js 文件下载 进度条

    js: /** * 下载文件 - 带进度监控 * @param url: 文件请求路径 * @param params: 请求参数 * @param name: 保存的文件名 * @param pro ...

  3. sublime使用技巧

    引用自:https://www.cnblogs.com/xiayuhao/p/9000216.html https://www.cnblogs.com/ma-dongdong/p/7653231.ht ...

  4. php结合layui实现前台加后台操作

    一:前台加载出前端页面: HTML: lay-data="{width:800,height:400, url:'data.php', page:true, id:'test'} js: l ...

  5. canvas 实现掉落效果

    var canvas = document.getElementById('canvas'); var cxt = canvas.getContext('2d'); cxt.strokeStyle = ...

  6. 进度条的制作unity

    不说了直接上代码: LoadingPanel: using UnityEngine;using System.Collections;using UnityEngine.UI;using UnityE ...

  7. 844. Backspace String Compare

    class Solution { public: bool backspaceCompare(string S, string T) { int szs=S.size(); int szt=T.siz ...

  8. 使用Wireshark分析网络数据

    一. Wireshark中查看TCP的三次握手和四次挥手: 上面的数据发送和接收两部分的info提示都是 [TCP segment of a reassembled PDU],网上的解释是TCP分片的 ...

  9. Mysql中Left Join Right Join Inner Join where条件的比较

    建立一对多的表 company 和 employee company表 id      name      address 1baidu北京 2huawei深圳 3jingdong北京 4tengxu ...

  10. form表单序列化为json格式数据

    在web开发过程中,经常遇到将form序列化不能格式的字符串提交到后台,下面就介绍怎样将form表单序列化为json字符串. 首先,是扩展的jquery序列化插件,依赖jquery.经测试,这段代码可 ...