In this article I will explain with an example, how to read Connection String from AppSettings.json file inside Startup.cs class in .Net Core 5 and ASP.Net Core 5.
Microsoft has replaced System.Configuration class with IConfiguration interface in .Net Core 5.
What is IConfiguration
The IConfiguration is an interface for .Net Core 5.
The IConfiguration interface need to be injected as dependency in the Controller and then later used throughout the Controller.
The IConfiguration interface is used to read Settings and Connection Strings from AppSettings.json file.
Namespaces
You will need to import the following namespace.
using Microsoft.Extensions.Configuration;
Adding the AppSettings.json file
In order to add AppSettings.json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button.
Once the File is created, it will have a DefaultConnection, below that a new Connection String entry is added.
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true",
"MyConn": "Data Source=.\\SQL2022;Initial Catalog=Northwind;Integrated Security=true"
}
}
Reading Connection String from AppSettings.json file inside Startup class
In the below example, the IConfiguration is injected in the Startup class and assigned to the private property Configuration.
Then inside the ConfigureServices method, the Connection String is read from the AppSettings.json file using the GetConnectionString function.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
string conStr = this.Configuration.GetConnectionString("MyConn");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Screenshot
Downloads