Old*_*zer 7 c# asp.net-core-mvc asp.net-core
根据http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/,事情发生了变化.但是,我无法从该文档中了解如何读取appSettings密钥.虽然有一个从ini文件读取的例子.
如何避免使用旧的System.Configuration.ConfigurationManager来读取AppSettingsweb.config中的键值?
将json文件添加到项目根目录:config.json
{
"AppSettings": {
"TestKey" : "TestValue"
}
}
Run Code Online (Sandbox Code Playgroud)
class为配置反序列化创建一个新的:
public class AppSettings
{
public string TestKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在Startup.cs:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvc();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
Run Code Online (Sandbox Code Playgroud)
获取您的选项controller:
public HomeController(IOptions<AppSettings> settings)
{
var value = settings.Value.TestKey;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2247 次 |
| 最近记录: |