asp.net-corevariablesasp.net-core-mvcpersistenceapplication-data

How to preserve variable value between application starts in ASP.Net Core MVC?


I have an ASP.NET Core MVC application that might be restarted from time to time (maintenance); how can make some variable values persistent from an execution to the next?

PS: That's the code that needs to write value as persistent. For example "LastMaintenanceRestartTime = 03/04-2020", the maintenance restart occurs once a day so the code needs to remember the last time it was restarted.

In UWP, I could do the following code but I can't seem to find an equivalent for ASP.NET Core:

Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] = value;

The best I could find is the following code but the values are only persistent within the same execution:

AppDomain.CurrentDomain.SetData(key, value);

Some talk about "Application.Settings" but I can't seem to be able to reach this namespace...

I've also seen some people talking about "AppSettings" files that can be modified during execution but it seems rather complex to keep a simple value persistent...

Do you have any recommendation, solution or ideas for me?


Solution

  • I found the solution:

    static void ReadSetting(string key)  
            {  
                try  
                {  
                    var appSettings = ConfigurationManager.AppSettings;  
                    string result = appSettings[key] ?? "Not Found";  
                    Console.WriteLine(result);  
                }  
                catch (ConfigurationErrorsException)  
                {  
                    Console.WriteLine("Error reading app settings");  
                }  
            }  
    
            static void AddUpdateAppSettings(string key, string value)  
            {  
                try  
                {  
                    var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
                    var settings = configFile.AppSettings.Settings;  
                    if (settings[key] == null)  
                    {  
                        settings.Add(key, value);  
                    }  
                    else  
                    {  
                        settings[key].Value = value;  
                    }  
                    configFile.Save(ConfigurationSaveMode.Modified);  
                    ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);  
                }  
                catch (ConfigurationErrorsException)  
                {  
                    Console.WriteLine("Error writing app settings");  
                }  
            }  
    

    Link: https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?redirectedfrom=MSDN&view=dotnet-plat-ext-5.0#System_Configuration_ConfigurationManager_AppSettings