<< Back to Blog

11 DECEMBER 2019

.NET Core: How to access AppSettings or Configuration within Razor View

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:

  1. Add a new section to your AppSettings.json (or AppSettings.development.json) file. Skip this if you only want to configure the value through Azure application settings.
    “CustomBannerOptions”: {
        “ShowBanner”: true
  1. Add a new custom class in your project with the same name as the custom section you have added.
public class CustomBannerOptions
    public bool ShowBanner { get; set; }
  1. Hook up the new CustomBannerOptions class in the ConfigureServices method of the Startup.cs file
services.Configure<CustomBannerOptions>(options => configuration.Bind(nameof(CustomBannerOptions), options));
  1. Inject 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;