'How to read web.config file in .Net Core app
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
Solution 1:[1]
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%.
Solution 2:[2]
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"];
}
}
Solution 3:[3]
In case you missed it - and because @Zuhair doesn't seem to want to post an answer - here is a copy paste of their solution (I missed this at first as it was only in a comment):
I found the solution. I changed the name of the Web.config to app.config and I was able to get the connection string using:
System.Configuration.ConfigurationManager.ConnectionStrings["SHOPPINGCNN"].ConnectionString
The app.config file looks like this:
<?xml version="1.0"> encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SHOPPINGCNN" connectionString="server=.\SQLEXPRESS;integrated security=true;database=xxxxx" />
</connectionStrings>
</configuration>
You also need to install this NuGet package:
System.Configuration.ConfigurationManager
In my case I simply renamed the web.config containing the connectionString 'app.config' and it worked.
I realise this probably isn't a good long term solution but for mixed legacy projects - or to get a foot in the door to begin to learn .net Core it's very useful.
Solution 4:[4]
For .NET Core apps, the best way is to use the Configuration API. This is a very flexible way and, thanks to providers pattern, it allows to use a different sources, not only the most common appsettings.json
file (that by the way just a JSON file and could be named in a random way):
- File formats (INI, JSON, and XML)
- Command-line arguments
- Environment variables
- In-memory .NET objects
- An encrypted user store Azure Key Vault
- Custom providers, which you install or create
Now about ConfigurationManager
. At first, the .NET Core forced to forget about this class - it was not implemented and supported and the idea was to fully replace it by providing new Configuration API.
Moreover, the reality is that ASP.NET Core apps aren't hosted via IIS anymore (IIS works mainly as a reverse proxy now), and so the web.config
is not so useful anymore (unless rare cases when you still need to define parameters specific to IIS configuration).
Though, after the .NET Standard 2.0 was provided, this System.Configuration.ConfigurationManager nuget package is available and brings back the ConfigurationManager
class. It became possible due to new compatibility shim implemented in new .NET Core 2.0.
Regarding your case, it is difficult to say why you have 'null' as it not enough information:
- it may be a wrong section in web.config
- web.config may not be copied into your output/publishing folder
Solution 5:[5]
For everyone having problem reading web.config in asp.net core. After spending hours trying and failing.. then i came to a blog which stated
The .Net Core application uses appsettings.json instead of web.config file.
so i suggest everyone to place files they want to read to appsettings.json and from there you can read. There are plenty of methods available. Just wanted to save time of those trying.
Solution 6:[6]
The problem here is that the OP has a data access layer project library that targets the full .Net Framework that contains code which depends on the ConfigurationManager. ConfigurationManager knows nothing about configuration in .Net Core and thus cannot access values from the default configuration implementation, i.e. appsettings.json. Some answers note that you can add an app.config file to the .Net Core client, but this smells if we don't hold our nose.
The better solution would be to inject the connection string into the data access library. Especially if that library will be used by multiple clients.
Solution 7:[7]
The only way i could use a web.config was reading the file as a XML, and inputing the values into a ConfigurationManager object using the .AddInMemoryCollection(list) method.
//ConfigurationManager.cs
using System;
using System.Collections;
using System.Xml;
using Microsoft.Extensions.Configuration;
namespace sql_util {
public static class ConfigurationManager {
public static IConfiguration AppSettings { get; }
static ConfigurationManager() {
var list = new List<KeyValuePair<string, string>>();
XmlDocument xd = new XmlDocument();
xd.Load(Directory.GetCurrentDirectory() + "\\" + "web.config");
if (xd.GetElementsByTagName("appSettings").Count > 0) {
XmlNodeList confs = xd.GetElementsByTagName("appSettings")[0].ChildNodes;
for (int y = 0; y < confs.Count; y++) {
if (confs[y].Attributes != null) {
if (confs[y].Attributes[0] != null) {
list.Add(new KeyValuePair<string, string>(confs[y].Attributes[0].Value, confs[y].Attributes[1].Value));
}
}
}
}
AppSettings = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddXmlFile(Directory.GetCurrentDirectory() + "\\Web.config", false, true)
.AddInMemoryCollection(list)
.Build();
}
}
}
//Web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="smtp_server" value="127.0.0.1" />
//envia_mail.cs
using ConfigurationManager = sql_util.ConfigurationManager;
namespace anotacoes {
public class envia_email {
private string SmtpServer = ConfigurationManager.AppSettings["smtp_server"];
Solution 8:[8]
added Web.config file to root as i used in .net framework project.
ConfigurationManager.AppSettings["MySQL"]; works fine.
I changed my Web.config to App.config and my issues resolved immediately.
Solution 9:[9]
You can still use an app.config for connection strings if needed. Include the nuget package System.Configuration.ConfigurationManager.
Then to get a connection string you'd do this:
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString
As others have pointed out, connection strings are easily used from the appsettings.json file and this is the preferred method.
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 | Kenya |
Solution 2 | |
Solution 3 | |
Solution 4 | Set |
Solution 5 | Amir Dora. |
Solution 6 | gravidThoughts |
Solution 7 | antoine |
Solution 8 | praveen |
Solution 9 | Rich Wagenknecht |