'ASP.NET Core 6 how to access Configuration during startup
In earlier versions, we had Startup.cs class and we get configuration object as follows in the Startup file.
public class Startup
{
private readonly IHostEnvironment environment;
private readonly IConfiguration config;
public Startup(IConfiguration configuration, IHostEnvironment environment)
{
this.config = configuration;
this.environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
// Add Services
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Add Middlewares
}
}
Now in .NET 6 (With Visual Studio 2022), we don't see the Startup.cs class. Looks like its days are numbered. So how do we get these objects like Configuration(IConfiguration) and Hosting Environment(IHostEnvironment)
How do we get these objects, to say read the configuration from appsettings? Currently the Program.cs file looks like this.
using Festify.Database;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<FestifyContext>();
////////////////////////////////////////////////
// The following is Giving me error as Configuration
// object is not avaible, I dont know how to inject this here.
////////////////////////////////////////////////
builder.Services.AddDbContext<FestifyContext>(opt =>
opt.UseSqlServer(
Configuration.GetConnectionString("Festify")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/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.UseAuthorization();
app.MapRazorPages();
app.Run();
I want to know how to read the configuration from appsettings.json ?
Solution 1:[1]
WebApplicationBuilder
returned by WebApplication.CreateBuilder(args)
exposes Configuration
and Environment
properties:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;
WebApplication
returned by WebApplicationBuilder.Build()
also exposes Configuration
and Environment
:
var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;
Also check the migration guide and code samples.
Solution 2:[2]
In Program.cs
, the WebApplicationBuilder is created shown below.
var builder = WebApplication.CreateBuilder(args);
Once we have the builder created, the configuration is available.
Let's assume you have the default appSettings.json
in place. The example code below would return the configuration Default log level setting from the JSON configuration file.
builder.Configuration["Logging:LogLevel:Default"] // returns "Warning"
Once the app is running, you can access the Configuration settings via dependency injection in other classes of your application.
public MyClass(IConfiguration configuration)
{
var logLevel = configuration["Logging:LogLevel:Default"];
}
A nice feature worth considering it to create a class that represents your settings and then bind the configuration to an instance of that class type. For example, let's assume you create a new class called MyAppSettings
with the same structure as your appSettings.json
, you can do the following:
var myAppSettings = builder.Configuration.Get<MyAppSettings>();
string logLevel = myAppSettings.Logging.LogLevel.Default;
Solution 3:[3]
.NET 6 already gives builder object in Program.cs
var builder = WebApplication.CreateBuilder(args);
Just use this builder to access configuration and Environment as an example to get ConnectionString from app.settings.cs as follows:
builder.Services.AddDbContext<DataContext>( options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectiion"));
});
Solution 4:[4]
All you need is to add "builder." before your Configuration
Like:
builder.Services
.AddDbContext<FestifyContext>
(opt =>opt.UseSqlServer(builder.Configuration
.GetConnectionString("Festify")));
Solution 5:[5]
The following codes worked for me:
Program.cs:
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("conStr");
ConnectionString = connString;
...
partial class Program
{
public static string? ConnectionString { get; private set; }
}
calling class:
string cnStr = Program.ConnectionString;
Solution 6:[6]
This worked for me ---
// Read in from JSON file
builder.Services.Configure<ConnectionKeys>(builder.Configuration.GetSection("ConnectionKeys"));
Solution 7:[7]
//.NET6 Program.cs -(to get the application configuration properties)
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"appsettings.Dev.json", optional: true);
builder.Configuration.AddEnvironmentVariables();
// projectwide instances
public IConfiguration _configuration;
public AccountsAPIController(IConfiguration configuration)
{
_configuration = configuration;
}
// _configuration.GetConnectionString("DefaultConnection");
Solution 8:[8]
This is slightly different than prior answers and I include this since I was reviewing something like this.
In your Program.cs
you can also group code in a method and call that to keep it less run-on a bit or to group similar things. I will not put all the code in; I will not put a full list of using
directives here but just enough to demonstrate the technique and I will leave out some method code. This is not enough or even perhaps too much for your solution and will need your custom touchup.
using AutoMapper;
using MicroKnights.Log4NetHelper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
...
//all your using directives
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
//a variable to hold configuration
IConfiguration Configuration;
var builder = WebApplication.CreateBuilder(args);
Configuration = builder.Configuration;
// call some methods
ConfigureAuth(builder.Services);
ConfigureRedis(builder.Services);
ConfigureSession(builder.Services);
ConfigureMvc(builder.Services);
ConfigureServices(builder.Services);
var app = builder.Build();
ConfigureMiddleWare(app);
app.Run();
// we are done with the main part, now the methods
void ConfigureMvc(IServiceCollection services)
{
builder.Services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
config.Filters.Add(new AuthorizeFilter(policy));
})
.AddRazorPagesOptions(options => { options.Conventions.AddPageRoute("/Home/Login", ""); })
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
}
void ConfigureSession(IServiceCollection services)
{
builder.Services.AddSession(options =>
{
options.Cookie.Name = "mygreatsite_session";
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
}
void ConfigureRedis(IServiceCollection services)
{
var redisConfig = new RedisOptions();
Configuration.GetSection(RedisOptions.RedisConfig).Bind(redisConfig);
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConfig.ConnectionString;
options.InstanceName = "mygreatsite_";
});
services.AddDataProtection()
.SetApplicationName("MyGreatSite.Website")
.PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.ConnectionString), "DataProtection-Keys");
}
void ConfigureMiddleWare(WebApplication app)
{
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseRouting();
app.UseCors("default");
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute().RequireAuthorization();
endpoints.MapControllerRoute(
name: "Default",
pattern: "{controller=Home}/{action=Login}"
);
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Peter Csala |
Solution 4 | ΩmegaMan |
Solution 5 | Kwami |
Solution 6 | Guru Stron |
Solution 7 | ΩmegaMan |
Solution 8 | Mark Schultheiss |