How to read web.config file in .Net Core app
in .net core you can use ConfigurationBuilder
to read appsettings.json file.
You can implement like following.
appsettings.json sample
{
"option1": "value1_from_json",
"option2": 2,
"ConnectionStrings": {
"YourConnectionString": "............."
}
}
C# code sample
static class YourClass
{
public static IConfigurationRoot Configuration;
public static string GetConnectionString()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
var connectionString = Configuration["ConnectionStrings:YourConnectionString"];
}
}
Because .Net Core applications are self hosted and can almost run on any platform, they are no longer hosted on IIS. The .Net Core application settings are stored in a Json
format (appsettings.json
) by default while .Net Framework application configurations are stored in a web.config
file in XML
format. For more info about .Net Core applications, you may read Configuration in ASP.NET Core. In my case, I was trying to access the data layer of a .Net Framework assembly from a .Net Core 2.0 assembly. To achieve this, there is no need to install System.Configuration.ConfigurationManager package in the .Net Core application but you only need to add app.config
to the .Net Core assembly then add the connection string to it:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="SHOPPINGCNN" connectionString="server=your server name;integrated security=true;database=your database name" />
</connectionStrings>
</configuration>
After that, everything will work fine. Make sure that you use the same connection string name (SHOPPINGCNN
in my case) that you used in your .Net Framework application otherwise you will not get the desired result. I did this in my project and it works 100%.