Reputation: 167
i have an issue about extract value from appsetting.json
appsetting.json
"Negozi": {
"PerPage": 10,
"Order": {
"By": "Name",
"Ascending": false,
"Allow": ["Nome", "Citta"]
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//useless code for this question
...
//Options
services.Configure<NegoziOptions>(configuration.GetSection("Negozi"));
}
NegoziOptions.cs
public class NegoziOptions
{
public int PerPage { get; set; }
public NegoziOrderOptions Order { get; set; }
}
public class NegoziOrderOptions{
public string By { get; set; }
public bool Ascending { get; set; }
public string Allow { get; set; }
}
}
Then I want to extract data and this is my method
public class EfCoreNegoziService : INegoziService
{
private readonly C3PAWMDbContext dbContext;
private readonly IOptionsMonitor<NegoziOptions> negozioOptions;
public EfCoreNegoziService(C3PAWMDbContext dbContext, IOptionsMonitor<NegoziOptions> negozioOptions)
{
this.negozioOptions = negozioOptions;
this.dbContext = dbContext;
}
public async Task<List<NegozioViewModel>> GetNegoziAsync(string search, int page)
{
search = search ?? "";
page = Math.Max(1, page);
int limit = negozioOptions.CurrentValue.PerPage;
int offset = (page - 1) * limit;
/*
Other code
*/
}
Im trying to debug but this is equals to 0
int limit = negozioOptions.CurrentValue.PerPage;
I have already take data from appsetting.json like ConnectionsStrings and it works fine but i can't understand why I can't extract from Negozi
Upvotes: 0
Views: 130
Reputation: 5861
Your Negozi
property in appsettings.json
format is not match with NegoziOptions
class.
Allow
property in appsettings.json
is array of strings and Allow
property in NegoziOrderOptions
class is string.
You should change type of Allow
to array of string in NegoziOrderOptions
.
Your NegoziOptions
class should be like this
public class NegoziOptions
{
public int PerPage { get; set; }
public NegoziOrderOptions Order { get; set; }
}
public class NegoziOrderOptions
{
public string By { get; set; }
public bool Ascending { get; set; }
public string[] Allow { get; set; }
}
your appsettings.json
should be like this
{
"Negozi": {
"PerPage": 10,
"Order": {
"By": "Name",
"Ascending": false,
"Allow": [
"Nome",
"Citta"
]
}
}
}
And Configure method:
services.Configure<NegoziOptions>(a => configuration.GetSection("Negozi").Bind(a));
Upvotes: 2