Reputation: 109
I have a class like this:
public class GameSettingOptions
{
public const string GameSettings = "GameSettings";
public int gameId { get; set; }
public string iconSize { get; set; }
public int sortOrder { get; set; }
public string[] chips { get; set; }
}
and a GameSettingsOptions.json file like this:
{
"GameSettings": [
{
"gameId": 1,
"iconSize": "big",
"sortOrder": 6
},
{
"gameId": 2,
"iconSize": "small",
"sortOrder": 4
},
{
"gameId": 3,
"iconSize": "medium",
"sortOrder": 2
},
{
"gameId": 4,
"iconSize": "small",
"sortOrder": 5
},
{
"gameId": 5,
"iconSize": "small",
"sortOrder": 8,
"chips": []
},
{
"gameId": 6,
"iconSize": "small",
"sortOrder": 7
},
{
"gameId": 7,
"iconSize": "big",
"sortOrder": 1,
"chips": []
},
]
}
I am trying to use the Options pattern to return these game settings through a controller like this:
public class GameSettingsControllers : ControllerBase
{
private readonly GameSettingOptions _gameSettingOptions;
public GameSettingsControllers(IOptions<GameSettingOptions> gameSettingOptions)
{
_gameSettingOptions = gameSettingOptions.Value;
}
public object GetGameSettings()
{
return Content ($"gameId: {_gameSettingOptions.gameId}" + $"iconSize: {_gameSettingOptions.iconSize}"
+ $"sortOrder: {_gameSettingOptions.sortOrder}" + $"chips: {_gameSettingOptions.chips}");
}
}
This is how I set up my Startup.cs file to use dependency injection on the IOptions
class:
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>(options => Configuration.GetSection(GameSettingOptions.GameSettings).Bind(options));
}
However the controller always returns null. I have no idea if I am using the wrong method inside the Configuration interface or not. The problem seems to lie in the binding between the JSON file and the GameSettingOptions class. Therefore currently the API keeps returning this:
gameId: 0iconSize: sortOrder: 0chips:
What I get from debugging what the Configuration returns
Upvotes: 0
Views: 1381