How to read appsettings.json or web.config with ServiceStack ASP.Net Core?
IAppSettings appSettings = new AppSettings();
appSettings.Get<string>("Hello");
does not find anything.
ServiceStack's default AppSettings for .NET Core can read <appSettings/>
, SimpleAuth.Mvc web.config is an example project that uses this.
With the new ServiceStack v5 that's now available on MyGet you can choose to instead use .NET Core's IConfiguration
model with the new NetCoreAppSettings
IAppSettings adapter.
.NET Core's IConfiguration
class is automatically pre-configured when running your .NET Core app using the recommended .NET Core 2.0 Startup config, ie:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Where you can request to get it injected into the Startup constructor and assign it to a property with:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) => Configuration = configuration;
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseServiceStack(new AppHost
{
AppSettings = new NetCoreAppSettings(Configuration)
});
}
}
Then you can get ServiceStack to use it with the NetCoreAppSettings
adapter as seen above.
This works as a normal IAppSettings
which you can use to read individual config values, eg:
public class AppHost : AppHostBase
{
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
});
}
}
Or bind to complex Types using the IAppSettings.Get<T>()
APIs.
An example .NET Core 2.0 ServiceStack v5 project that uses it is NetCoreTemplates/react-spa .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.