How to read web.config file in .Net Core app

Zuhair picture Zuhair · Oct 29, 2017 · Viewed 26.9k times · Source

I have created a .Net Core API and I referenced a .Net framework application to it. The referenced Application connects to a data base and its connection string is stored in web.config file:

    string CONNSTR =ConfigurationManager.ConnectionStrings["SHOPPINGCNN"].ConnectionString;

The .Net Core application uses appsettings.json instead of web.config file. When I run the API and try to use the referenced application resources, the above code will be triggered and will return null because there is no web.config file exists in .net Core app. What is the best solution to resolve this issue

Answer

Zuhair picture Zuhair · May 28, 2018

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%.