11 DECEMBER 2019
ASP.Net Core ‘inject’ functionality allows you to add code into the view safe in the knowledge that it will be compiled before the code is deployed.
To access a configuration value in a view:
{
“AppSettings”:{
...
},
“CustomBannerOptions”: {
“ShowBanner”: true
}
}
public class CustomBannerOptions
{
public bool ShowBanner { get; set; }
}
CustomBannerOptions
class in the ConfigureServices method of the Startup.cs fileservices.Configure<CustomBannerOptions>(options => configuration.Bind(nameof(CustomBannerOptions), options));
IOptions<CustomBannerOptions>
into your View. Now you can access the new configuration values in the View. This means we only have access to the config items we need which is preferable over injecting the full AppSettings object.@using STF.Web.Code.Configuration;
@using Microsoft.Extensions.Options;
@inject IOptions<CustomBannerOptions> BannerOptions;
@{
// Should default to false if value doesn’t exist
bool showBanner = BannerOptions.Value.ShowBanner;
}