Using App.Config in .Net Core

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app.
    Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

get data from App.config file in asp.net core 3.1

SOLUTION
To solve your problem add the App.config file to the ENTRY POINT project.

This is your executable project like WinForms or WPF or Console App.

Not to the Class Library project.

The reason is when the app compiles the App.config gets renamed to "MyProjectName.Ext.config".

For example if you have Class Library project called ConfigUtils the file will be output as ConfigUtils.dll.config.

But ConfigurationManager expects the name of the entry point plus config.

So if your ConfigUtils is referenced from let's say MyApp Console project. Then the ouput file will be MyApp.exe.config

So for the ConfigurationManager to work right off without any further meddling you need to place your App.config file in the entry point project.

.NET CORE WAY
I recommend NOT to use ConfigurationManager...

Just use the new way of doing it!

To demonstrate how to do it in .NET Core I created a console app using .NET Core 3.1.3
I added also an extension method to wrap up the functionality for reusability.

First my code:

    using Microsoft.Extensions.Configuration;
using System;

class Program
{
private static IConfiguration _configuration;
static void Main(string[] args)
{
_configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.Build();

var itemsPerPage = _configuration.GetValue<int>("appSettings", "DefaultItemsPerPage");
Console.WriteLine("Items Per Page:" + itemsPerPage.ToString());
Console.ReadLine();
}
}
public static class ConfigExtenstions
{
public static T GetValue<T>(this IConfiguration configuration, string configSection, string keyName)
{
return (T)Convert.ChangeType(configuration[$"{configSection}:{keyName}"], typeof(T));
}
private static T GetValue<T>(string configSection, string configSubSection, string keyName)
{
return (T)Convert.ChangeType(Configuration[$"{configSection}:{configSubSection}:{keyName}"], typeof(T));
}
}

My appsettings.json file looks like this:

{
"appSettings": {
"DefaultItemsPerPage": 3
}
}

The confuguration file can be modeled however you want. In this case I made it look like your app.config file.

Also I right clicked on the appsettings.json file in visual studio and set to "Copy Always".

For all of this to work you need to add 2 NuGet packages like this:

Sample Image

NOTES:
You can use other "Providers" to pull configuration from XML, INI and other types of files and sources. For that you need to add other NuGet packages etc.

This link even though it talks about ASP.NET Core Configuration it is very useful because the same concepts apply.

Is using app.config and ConfigurationManager in .NET core advisable?

Some history, the original team to begin shrinking the dependencies included in a .Net application was the Asp.Net team. Microsoft's web framework was bloated compared to more modular frameworks, causing latency in request. According to Scott Hansleman whom frequently tells this joke in presentations:

Who here develops with .Net? Nobody under thirty, fantastic! So how do
we combat this? Become modular, faster, cross platform, and easier to
get started. Otherwise you would go, I want to learn to code.
Download Visual Studio then four hours later write hello world.

So the web team began this transformation, which for the web makes JavaScript Object Notation a better choice than Extended Markup Language. But within a year of the Asp.Net team making these modifications Microsoft restructured their organization for a one .Net. They realized that these changes would cascade across more than just the Asp.Net team. The older project types would not be compatible or work with JavaScript Object Notation, so they transitioned back to Extended Markup for their .csproj and other configuration types. But a lot of developers really liked the JavaScript Object Notation files for settings, they are smaller, clearer, and not as verbose. So Microsoft added the feature back through Microsoft.Extensions.Configuration to allow you the flexibility.

  • The primary purpose was for backwards compatibility.
  • Ensure that it is updated for any .Net Standard application as well.

So you can leverage either. No real benefit, aside from Extended Markup tends to be incredibly tedious to read and verbose compare to a JavaScript Object. JavaScript Object Notation tends to be easier.

Common Configuration strategy for .Net Framework and .Net Core

Please take a look at Configuration providers in .NET. All the samples are intended to be used with .NET Core, but most of the NuGet packages are compatible with .NET Standard 2.0. Therefore you should be able to consume them from any .NET Framework application being compatible to .NET Standard 2.0.

Your code could look a bit like this:

var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddXmlFile("App.config", optional: true, reloadOnChange: true);
var config = configurationBuilder.Build();

From that on, you can work with the unified config object.

Disclaimer: I didn't test it, but I'm quite confident /p>

Reading settings from app.config or web.config in .NET

You'll need to add a reference to System.Configuration in your project's references folder.

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.



Related Topics



Leave a reply



Submit