问题描述
id Cost LineNo TotalCost
----------------------- ---------
1 10 01 10
2 20 02 40
3 30 03 150
我正在尝试从这样设置的服务中检索它:
public class GameSettingOptions
{
public int gameId { get; set; }
public string iconSize { get; set; }
public int sortOrder { get; set; }
public string[] chips { get; set; }
}
这是我的 json 对象,其中游戏设置是一个数组:
public Startup(IConfiguration configuration,IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile("GameSettingOptions.json",optional: true,reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin",options => options.AllowAnyOrigin());
});
services.Configure<GameSettingOptions>(Configuration.GetSection("GameSettings"));
}
这就是我尝试使用此控制器和依赖项注入来检索它的方式
{
"GameSettings": [
{
"gameId": 1,"iconSize": "big","sortOrder": 6
},{
"gameId": 2,"iconSize": "small","sortOrder": 4
}
]
}
我尝试过的:
public class GameSettingsControllers : ControllerBase
{
private readonly GameSettingOptions Options;
public GameSettingsControllers(IOptionsSnapshot<GameSettingOptions> options)
{
Options = options.Value;
}
public object GetGameSettings()
{
return new JsonResult($"gameId: {Options.gameId}," + $"iconSize: {Options.iconSize},"
+ $"sortOrder: {Options.sortOrder}," + $"chips: {Options.chips} ");
}
}
services.Configure<List<GameSettingOptions>>(Configuration.GetSection("GameSettings"));
IOptions<List<GameSettingOptions>>
- 对于控制器,我尝试对 IOptions 值执行 foreach,但它说 GameSetingsOptions 敌人不包含公共实例或“GetEnumerator”的定义
解决方法
请定义GameSettingsOtions
,如下所示
public class GameSettingOptions: List<GameSetting>
{
}
public class GameSetting
{
public int gameId { get; set; }
public string iconSize { get; set; }
public int sortOrder { get; set; }
public string[] chips { get; set; }
}
现在来配置它,使用下面的代码 ConfigureServices
方法:
services.Configure<GameSettingOptions>(options => Configuration.GetSection("GameSettings").Bind(options));
上面你可以看到定义的选项被注入。这是我调试的截图:
这是我的 appsettings.json 文件以供参考:
{
"Logging": {
"LogLevel": {
"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
}
},"AllowedHosts": "*","MySettings": {
"SettingValue": 2
},"GameSettings": [
{
"gameId": 1,"iconSize": "big","sortOrder": 6
},{
"gameId": 2,"iconSize": "small","sortOrder": 4
},{
"gameId": 3,"iconSize": "medium","sortOrder": 2
},{
"gameId": 4,"sortOrder": 5
},{
"gameId": 5,"sortOrder": 8,"chips": []
},{
"gameId": 6,"sortOrder": 7
},{
"gameId": 7,"sortOrder": 1,"chips": []
}
]
}