Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 876
Zuhair Avatar asked Oct 29 '17 03:10

Zuhair


People also ask

Can I use Web config in .NET Core?

The web. config file has also been replaced in ASP.NET Core. Configuration itself can now be configured, as part of the application startup procedure described in Startup.


1 Answers

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

like image 179
Zuhair Avatar answered Sep 20 '22 15:09

Zuhair