Access Configuration from a View in ASP.NET Core

Let’s talk about the scenario, you have configured the Application Title into AppSettings.JSON

1) AppSettings.JSON

{
"AppSettings":{
"ApplicationTitle":"My Application"
},
"ConnectionStrings":{
"DefaultConnection":"Default connection string"
},
"Logging":{
"IncludeScopes":false,
"LogLevel":{
"Default":"Warning"
}
}
}

To use the configuration settings, we have to make sure that the appsettings.json file is loaded to Configuration Builder, which is used to build the configuration of key/value-based settings.

2) Go to the Startup.CS file

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
             .SetBasePath(env.ContentRootPath)
             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
             .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }

3) ApplicationSettings class

We can get all the configuration settings in the form of strongly typed objects.

Create a Configuration folder in the web project and place the ApplicationSettings class to hold the configuration values

public class ApplicationSettings
{
   public string ApplicationTitle { get; set; }
}

Now to make the instance of the ApplicationSettings class hold the actual configuration values,
we need to Inject IOptions and configure the ApplicationSettings instance to hold the value from the AppSettings section of appsettings.json.

4) Configure Dependency Injection for IOptions Pattern

Go to Startup.CS

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddControllersWithViews();

            services.AddRazorPages();

            services.AddMvc();

            services.AddOptions();

            services.Configure<Configuration.ApplicationSettings>(Configuration.GetSection("AppSettings"));
        }


5) To use the configuration in a View, inject the IOptions into the view

@inject IOptions _configurationSettings

@_configurationSettings.Value.ApplicationTitle

6) To use the configuration in a Controller, we have to inject IOptions<ApplicationSettings)

//Add Microsoft.Extensions.Options to resolve the IOptions<> pattern

private IOptions<ApplicationSettings> _settings;

public HomeController(IOptions<ApplicationSettings> settings)
{
 _settings = settings;
}

public IActionResult Index()
{
 // Usage of IOptions
 ViewBag.Title = _settings.Value.ApplicationTitle;
 return View();
}

Happy Programming!!

Leave a Reply

Discover more from AI Infrastructure Architect & Enterprise Solution Architect

Subscribe now to keep reading and get access to the full archive.

Continue reading