简体   繁体   中英

Decrypting app.config connection strings in .Net Core 3.1

I have the following code for a console application:

        // Get the app config file.
        var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        // Get the sections to unprotect.
        ConfigurationSection connStrings = configuration.ConnectionStrings;

        string connection = null;

        if (connStrings != null)
        {
            // UNPROTECT
            connStrings.SectionInformation.UnprotectSection();

            connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        }

This code works just fine on Framework 4.8, but when I try it on Core 3.1, it throws "PlatformNotSupportedException" at the "UNPROTECT" code.

This is on the same work station and everything.

The official documentation for both ConfigurationManager and SectionInformation shows compatibility with Core 3.0 and 3.1.

I'm guessing that the classes are "compatible" with Core for convenience of accessing the config file but the decryption is not because the keys for decryption are stored in the Framework, but Core is cross platform and therefore won't have access to the keys. (Yes?)

If this platform doesn't support decryption of connection strings, is there some preferred alternative to encrypting/decrypting connection strings?

I have looked high and low but don't seem to be able to find anything.

NOTE: The ability to decrypt the encrypted connection string is essential!

Thanks.

The ConfigurationManager class has been deprecated in DotNetCore, it has been replaced with the IConfiguration class which you can construct with the ConfigurationBuilder class, here's an example of loading a json file (just a note that you need two nuget dependencies for this which are Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json ):


var config = new ConfigurationBuilder()
    .AddJsonFile("Config.json", true) // bool to say whether it is optional
    .Build()

As mentioned this will give you an instance of the IConfiguration class which is documented here but is very similar to the ConfigurationManager

example of config.json :

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM