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

2019-01-19 12:39发布

问题:

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

回答1:

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"];

    }

}


回答2:

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


回答3:

Because .Net Core applications are self hosted and can almost run on any platform , they are no longer hosted on ISS. 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>

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



回答4:

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.