I have a text string I want to persist in a WCF web service. What is the best practice for storing it between sessions and between reboots/restarts of IIS?
Storing it in a text file on the operating system? Or is there a built in persistence object?
This string is a piece of text I need to return from the web service and occasionally update via a call being made to the web service. (The web service has a Read Only database back end, so I don't have the option to save this string to a database--without adding a separate database call and I'd rather avoid that extra point of failure.)
You mean a connection string? web.config
Or a password, or key? web.config
Something that's displayed to the user? resource table
Ps I ended up using the web.config solution. For those interested in doing what I did here's the hoops I jumped through:
1) Set up a directory under the web application's root and opened that up to write permission to the IISUser. (Used a sub directory to avoid compromising security in the main application directory) Then added the following to the top of my source code:
System.Configuration.Configuration _webConfig =
WebConfigurationManager.OpenWebConfiguration("~\\directory_where_IISUser_has_write_permisions\\");
2) Namespaces needed:
using System.Web.Configuration;
using System.Configuration;
3) Code to create a new setting. The try/catch handles when the setting doesn't exist. Yes, it's a total hack. If someone knows how to check for the existence of the setting please let me know in a comment!
try
{
_webConfig.AppSettings.Settings["SettingName"].Value = textMessage;
} catch {
_webConfig.AppSettings.Settings.Add("SettingName", textMessage);
}
_webConfig.Save(ConfigurationSaveMode.Modified);
4) Code to read:
TextMessage = _webConfig.AppSettings.Settings["SettingName"].Value;
EDIT:
You can do something like:
bool bKeyExists = false;
foreach (SettingsProperty settingsProperty in appSettings.Properties)
{
if (settingsProperty.Name == _strKey)
{
bKeyExists = true;
break;
}
}
Or, with LINQ:
bool bKeyExists = appSettings.Properties.Cast<SettingsProperty>().Where(x => x.Name == _strKey).FirstOrDefault() != null;
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.