asp.net core 读取appsetting中的集合
1.首先在appsetting中定义集合 Roles
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "Roles": [ {"key": "admin","value": "系统管理员"}, { "key": "manageCourse", "value": "学科组长" }, { "key": "ctr", "value": "教师" } ] }
2.定义实体类 Roles.cs
public class Roles { public string key { get; set; } public string value { get; set; } }
3.在startup.cs中配置
public void ConfigureServices(IServiceCollection services)
{
services.Configure<List<Roles>>(this.Configuration.GetSection("Roles"));
}
4. controller中使用
public class LoginController : Controller
{
private readonly List<Roles> _roles = null; //定义
public IActionResult Index()
{
_roles.ForEach(item => { Console.WriteLine(item.key + "<-->" + item.value);} );
return View( );
}
public LoginController( IOptions<List<Roles>> Roles)
{
_roles = Roles.Value; //依赖注入
}
}
5.在startUp.cs 中直接使用
public static List<Roles> typeList;
public void ConfigureServices(IServiceCollection services )
{
typeList = Configuration.GetSection("Roles").Get<List<Roles>>() ;
typeList.ForEach(item => Console.WriteLine($"s={item.Key}-{item.Value}"));
}
6.请看输出结果