asp.net Core通过IConfiguration读取配置文件
Model类:
namespace dotnetcoremvc.Models { public class UserModel{ public string Name { get; set; } public string Pwd { get; set; } } }
appsettings配置文件
{"UserModel":{ "Name":"TestName", "Pwd":"4567" } }
StartUp类
public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { var UserModel = new UserModel();
//通过节点映射: Configuration.Bind("UserModel",UserModel);
//节点读取
// var data = configuration["UserModel"];
}
IConfiguration类提供了一个Bind方法。Bind方法可以通过Json文件配置节点和实体进行映射。因为默认读取的是appsettings.json文件这里就直接加载了。如果想配置其他的Json文件的话可以在Program.cs文件中自定义配置
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration(r=>r.AddJsonFile("other.json")) .UseStartup<Startup>() .Build();