Last active
January 27, 2020 14:00
-
-
Save oleksabor/6ae0627d6058efd33f815c9b10ef6c61 to your computer and use it in GitHub Desktop.
Using IEnumerable<> configuration class properties in the asp.net core 3.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Applications": { | |
"AppList": [ | |
{ | |
"Name": "test1", | |
"Roles": [ "readers", "writers" ] | |
} | |
] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.Configure<Applications>(options => Configuration.GetSection("Applications").Bind(options)); | |
var apps = services.BuildServiceProvider().GetService<IOptionsSnapshot<Applications>>(); | |
if (apps.Value.AppList == null || !apps.Value.AppList.Any()) | |
{ | |
var sample = new Applications(); | |
sample.AppList = new List<Application>() { | |
new Application { Name = "test1", Roles = new[] { "readers", "writers" } }, | |
new Application{ Name = "abracadabra", Roles = new[] { "magic", "hobbit" } }, | |
}; | |
var str = JsonConvert.SerializeObject(sample); | |
Console.WriteLine(str); | |
var apps2 = JsonConvert.DeserializeObject<Applications>(str); | |
if (!apps2.AppList.Any()) | |
throw new ArgumentException("appList fault Newtonsoft.Json"); | |
var apps3 = System.Text.Json.JsonSerializer.Deserialize<Applications>(str); | |
if (!apps3.AppList.Any()) | |
throw new ArgumentException("appList fault System.Text.Json"); | |
} | |
} | |
} | |
public class Application | |
{ | |
public string Name { get; set; } = ""; | |
public IEnumerable<string> Roles { get; set; } = new[] { "" }; | |
public Application ToApplicationWithoutPass() => | |
new Application | |
{ | |
Name = Name, | |
Roles = Roles.ToList().ToArray() | |
}; | |
} | |
public class Applications | |
{ | |
public IEnumerable<Application> AppList { get; set; } = new List<Application>(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment