使用asp.net核心的servicestack读取web.config

时间:2017-07-05 11:29:27

标签: c# asp.net-core web-config servicestack

如何使用ServiceStack ASP.Net Core阅读 appsettings.json web.config

IAppSettings appSettings = new AppSettings();
appSettings.Get<string>("Hello");

找不到任何东西。

1 个答案:

答案 0 :(得分:3)

ServiceStack的.NET Core默认AppSettings可以读取<appSettings/>SimpleAuth.Mvc web.config是一个使用它的示例项目。

使用.NET Core的IConfiguration配置模型

使用现在为new ServiceStack v5available on MyGet,您可以选择使用.NET Core的IConfiguration模型和新的NetCoreAppSettings IAppSettings适配器。

使用推荐的.NET Core 2.0 Startup配置运行.NET Core应用程序时,会自动预先配置.NET Core的IConfiguration类,即:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

您可以请求将其注入Startup构造函数并将其分配给属性:

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)
        });
    }
}

然后,您可以让ServiceStack与NetCoreAppSettings适配器一起使用,如上所示。

这可以作为普通IAppSettings使用,您可以使用它来读取单个配置值,例如:

public class AppHost : AppHostBase
{
    public override void Configure(Container container)
    {
        SetConfig(new HostConfig
        {
            DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
        });
    }
}

或使用IAppSettings.Get<T>() API绑定到复杂类型。

使用它的示例.NET Core 2.0 ServiceStack v5项目是NetCoreTemplates/react-spa

相关问题