I have a shared .NET Standard library that was originally being referenced by a .NET 4.8 MVC 4 project. There is a lot of code in this shared library that uses the ConfigurationManager, like:
var sze = ConfigurationManager.AppSettings["MaxAttachmentSize"];
This value for MaxAttachmentSize (and others) was being stored in the web.config.
Now I have a .NET 6 project that I'm building, which will use this same shared project, and I need to find a way to make these configuration app settings work in the new .NET Core application. What's the best way to do this?
My questions I guess are:
ConfigurationManager to read from the .NET Core's appsettings.json file like it reads from web.config in the ASP.NET MVC 4 project?The big spanner in the works though is the fact that all calls to ConfigurationManger right now are static, so if the .NET Core option could be static as well that would be incredibly helpful. If not, it'll just be more work moving the ASP.NET MVC 4 project to make those settings dependency injection available.
now you can get it even more easy
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
string sze = Configuration.GetSection("AppSettings:MaxAttachmentSize").Value;
after adding to appsettings.json
"AppSettings": {
"MaxAttachmentSize": "size1",
"MinAttachmentSize": "size2"
}
Using ASP .NET6
Install NuGet package System.Configuration.ConfigurationManager
The name of my configuration file is App.Config
Content of App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="DBConnectionString" value="aa" />
<add key="DBName" value="bb" />
<add key="AuthKey" value="cc" />
</appSettings>
</configuration>
File reading values, i.e. SettingsService.cs:
using namespc = System.Configuration;
namespace Ecommerce_server.Services.SetupOperation
{
public interface ISettingsService
{
string MongoDBConnectionString { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }
string DataBaseName { get => namespc.ConfigurationManager.AppSettings["DBName"]!; }
public string AuthKey { get => namespc.ConfigurationManager.AppSettings["AuthKey"]!; }
}
public class SettingsService : ISettingsService
{
public string MongoDBConnectionString { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }
public string DataBaseName { get => namespc.ConfigurationManager.AppSettings["DBName"]!; }
public string AuthKey { get => namespc.ConfigurationManager.AppSettings["AuthKey"]!; }
}
}
Note: We had to create a specialized namespace for ConfigurationManger to solve ambiguity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With