
正文
ServiceStack NetCoreAppSettings 配置文件读取和设置
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
假设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();
});
}
} 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", );
Console.WriteLine($"MaxRecords: {AppSettings.GetString("MaxRecords")}"); pageConfig.LightListPageSize = ;
pageConfig.GatewayListPageSize = ; //设置属性,然后读取对象
AppSettings.Set<int>("PageConfig:LightListPageSize", );
var pageConfig2 = AppSettings.Get<PageConfig>("PageConfig"); Console.WriteLine("设置配置完毕"); #endregion }
}
}
项目SSHost里添加配置文件appsettings.Json,里面配置内容如下
{
"MaxRecords": "",
"PageConfig": {
"LightListPageSize": "",
"GatewayListPageSize": ""
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
编译运行,出现如下错误信息
>------ 已启动全部重新生成: 项目: SSHost.ServiceModel, 配置: Debug Any CPU ------
>SSHost.ServiceModel -> D:\SSHost\SSHost.ServiceModel\bin\Debug\netstandard2.\SSHost.ServiceModel.dll
>------ 已启动全部重新生成: 项目: SSHost.ServiceInterface, 配置: Debug Any CPU ------
>SSHost.ServiceInterface -> D:\SSHost\SSHost.ServiceInterface\bin\Debug\netstandard2.\SSHost.ServiceInterface.dll
>------ 已启动全部重新生成: 项目: SSHost, 配置: Debug Any CPU ------
>------ 已启动全部重新生成: 项目: SSHost.Tests, 配置: Debug Any CPU ------
>SSHost.Tests -> D:\SSHost\SSHost.Tests\bin\Debug\netcoreapp2.\SSHost.Tests.dll
>Program.cs(,,,): error CS1061: “IConfigurationBuilder”未包含“AddJsonFile”的定义,并且找不到可接受第一个“IConfigurationBuilder”类型参数的可访问扩展方法“AddJsonFile”(是否缺少 using 指令或程序集引用?)
>已完成生成项目“SSHost.csproj”的操作 - 失败。
========== 全部重新生成: 成功 个,失败 个,跳过 个 ==========
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







