How to enable/disable logging on ASP.NET - asp.net

I'm trying to create a setup in my ASP.NET website that allows me to enable/disable logging while the application is running at any point. I figure some of you have already done such a thing.
Here's the gist of what i'm trying to do:
if(ShouldBeLogging)
logger.Info("helloooooo there");
So how would you set up the boolean value ShouldBeLogging to be able to be turned on/off while the website is running without getting any serious performance drawbacks(seeing how its going to be accessed frequently)?
I was thinking about putting something in the web.config, but wouldn't a change to that kick my user sessions if i wanted to turn it on?
Thanks!

I decided to go with log4net which supports this exact functionality. You can put a line in your assemblyinfo.cs like:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "config\\log4net.config", Watch = true)]
which will tell it to watch the config file for changes. then you can set the level node in the config xml at any time during the program's execution and the logging will be turned on/off, as long as you're using the following checks in your code:
if(log.IsDebugEnabled)
log.Debug("write a debug message to the logger");
see http://logging.apache.org/log4net/release/manual/internals.html for more info.

The built in diagnostics/tracing might be the best fit for your needs, i.e. see
http://www.beansoftware.com/ASP.NET-Tutorials/Tracing-ASP.NET.aspx
sample for web.config:
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="false" />
<authentication mode="Windows" />
<trace enabled ="true" pageOutput ="false" requestLimit ="20" traceMode ="SortByTime " />
</system.web>

Yes, a change to the web.config will result in the application restarting itself, and session being lost depending on your session store.
The performance overhead of a boolean check is minimum, but its a maintenance nightmare.
Why don't you just use Enterprise Library Logging Application Block, which is already externally configurable? A reference for what you are trying to do would be here Checking Filter Status before Logging
If you decide you really want to toggle logging via if checks a simple psuedo solution is to add a value to your web.config appSettings
<appSettings>
<add key="DiagnosticLogging" value="true" />
</appSettings>
And then in your Global Page
public static readonly Boolean LoggingEnabled { get;}
Application_Start(..){
string log = ConfigurationSettings.AppSettings["DiagnosticLogging"];
LoggingEnabled = false;
if(!string.IsNullOrEmpty(log)){
if(!boolean.TryParse(out LoggingEnabled )){
//bad application setting.. handle
}
}
}

Related

ASP.NET does not attempt to open web.config file?

I am trying to get my .aspx page to read from its web.config file. Code that works on other servers does not work as expected on one particular server (all machines involved are W2K3 R2 SP2).
A snippet of the .aspx is
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" Text="" ID="lblTime" /><br />
Value of myConfigTest is '<asp:Label ID="lblValue" runat="server" Text=""/>'
</div>
</form>
</body>
The code is here:
using System;
using System.Web.Configuration;
namespace configTestWeb
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToLongTimeString();
string value = WebConfigurationManager.AppSettings["myConfigTest"];
lblValue.Text = value;
}
}
}
And my web.config file is set thusly:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="myConfigTest" value="This is a test"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>
In an attempt to troubleshoot I setup ProcMon to filter on web.config and hit the page from a browser. The output is
1:06:04 PM
Value of myConfigTest is ''
But the really strange thing is that ProcMon never reports an attempt to access the file! If I right-click on the virtual directory in IIS and select Properties | ASP.NET | Edit Configuration I can see web.config being accessed with ~65 entries in ProcMon, and the appSetting is reported correctly in the ASP.NET Configuration Settings dialog.
I believe I've ruled out ACL's as an issue by
a) Setting the entire directory tree that the .aspx and web.config are in to Everyone | Full Permissions
b) ProcMon would report failed attempts to open the file if permissions were the issue
In desperation I uninstalled / reinstalled ASP.NET 4.0.
It may be noteworthy that reading configuration from an .exe works perfectly on that server using
string value = System.Configuration.ConfigurationManager.AppSettings[key];
This issue appears across multiple virtual directories.
So my question is, what might be preventing this one server from being able to read web.config files?
Rather than going to trouble of using ProcMon try doing a simpler test: Edit web.config file to enable the trace feature, then access website and see if it shows the request trace.
Add this to your web.config inside of system.web node:
<trace
enabled="true"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="false"
/>
By default changes to web.config (when file is saved/written to disk) will restart the ASP.NET application pool. These options can be changed, however, so if you do not see a change in your web app behavior after modifying web.config you can also try to stop and restart the service, or trigger an app pool recycle by using task manager to kill the aspnet_wp.exe process (I think this is what it is called in 2k3, if not try w3wp.exe instead), then make another request (refresh browser) to the web app and it IIS should start the app pool for ya.
If the changes (toggling between trace enabled=true and enabled=false) are not visible after saving web.config, but ARE visible after forcing stop/restart, then your IIS on that box may not have the option to restart app pool when configuration changes (don't have 2k3 in front of me, but in IIS 7 it is under Application Pools > Advanced Options > Recycling > "Disable Recyling for Configuration Changes" -- it is one of those annoying double-negative options, so "false" means recycle after config changes, and "true" means don't).
Update:
Dang, looks like IIS6 doesn't have that "for Configuration changes" option in the Recycling tab of the App pool properties sheet. Sorry, not sure where this setting is stored, doesn't appear to be in machine.config or web.config tho, so probably whatever IIS uses internally for the metabase stuff (registry maybe?)
If you try the trick for toggling trace and you don't see any effects, did you verify you are editing the correct web.config file?

Viewstate timeout error

I develop mostly for desktop so, I tend to think as WebForms as a web equivalent of WinForms. Unfortunetly this is not true.
Recently I have discovered that the Viewstate have some kind of timeout.
My problem is similar as I have read in most questions, in particular here (in my case is only around 5 to 10 minutes).
Here Microsoft says that one solution for this problem is:
<asp:Page EnableViewStateMac="False" />
However as we can read further they say:
Security Note:
This attribute should never be set to false in a production Web site,
even if the application or page does not use view state.
The view state MAC helps ensure the security of other ASP.NET functions
in addition to view state.
For this reason I don't want to set EnableViewStateMac to false and I have no access to my server (is shared hosting).
My question is: can we store the Viewstate between postbacks even if our page stay idle for a long time? If yes, how?
Thank you
The viewstate is encrypted using a machine key to ensure that it is not tampered with during postback. The machine key used to encrypt the viewstate is by default auto-generated and if the time out happens then the key's decryption will fail because the machinekey will get regenerated.
The machinekey is by default available at machine level config file.
<machineKey validationKey="AutoGenerate,IsolateApps"
decryptionKey="AutoGenerate,IsolateApps"
validation="SHA1" decryption="Auto" />
To fix this, you can use your own defined machine key. You can generate using online tools as well, like this or through IIS.
How to add this machinekey to web.config can be read at MSDN.
It should be placed under the system.web section, like this -
<configuration>
<system.web>
<machineKey decryptionKey="Decryption key goes here,IsolateApps"
validationKey="Validation key goes here,IsolateApps" />
</system.web>
</configuration>

New Asp.Net MVC5 project produces an infinite loop to login page

I am creating a brand new projet with Visual Studio 2013, I choose Asp.Net MVC and the framework 4.5.1 The project is created, then, I do nothing else than F5 to start the default web page. Unfortunately, it produces a redirect to the login page which is redirecting into the login page too. Here is a short version of the url I have in the browser:
http://localhost:5285/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252FAccount%25252FLogin%25253FReturnUrl%25253D%2525252FAccount%2525252FLogin%2525253FReturnUrl%2525253D%252525252FAccount%252525252FLogin%252525253FReturnUrl%252525253D%25252525252FAccount%25252525252FLogin%25252525253FReturnUrl%25252525253D%2525252525252FAccount%2525252525252FLogin%2525252525253FReturnUrl%2525252525253D%252525252525
I do not have any error in the Event Viewer. But in the screen I see :
"HTTP Error 404.15 - Not Found The request filtering module is
configured to deny a request where the query string is too long."
The website is running with the default setting in IIS Express. How can I fix this problem? I am guessing something is wrong with my Visual Studio 2013?
Edit
It works if I create a brand new website and I host it in IIS. But if I create a new website (without modifying anything) and just hit play (which start IIS Express by default), it doesn't.
Edit 2
I have deleted every websites in the Documents\IISExpress\config\applicationhost.config. I have recompiled everything, and it created this entry :
<siteDefaults>
<logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
<traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
</siteDefaults>
<applicationDefaults applicationPool="Clr4IntegratedAppPool" />
<virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>
I am still getting the error with IIS Express, not with IIS.
Highlight the project in Visual Studio
Open the 'Properties' panel on the right (or press F4)
Set 'Windows Authentication' to 'Disabled'
Set 'Anonymous Authentication' to 'Enabled'
You are missing [AllowAnonymous] attribute on login action.
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
// code....
}
2nd possibility, specific to IIS Express only: is that, if you created same default WebApplication1 project multiple times, playing with different authentication settings, IIS Express stored additional authentication settings in it's configuration file. Something like:
<location path="WebApplication1">
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
</location>
</configuration>
Configurations are in user's Documents folder Documents\IISExpress\config\, and you should look for:
applicationhost.config
Then just delete xml node <location path="WebApplication1"> mentioned above.
Update for VS 2015+
If you're using Visual Studio 2015 or higher, check this path for the config file:
$(solutionDir)\.vs\config\applicationhost.config
Each solution will have its own config file.
This issue is because of the authentication mode selected(by default) by the MVC 5 Template, which triggers the ReturnUrl Style of redirection that might lead to an infinite loop if not configured correctly.
To disable OWIN startup discovery,add this key to your webconfig file.
<add key="owin:AutomaticAppStartup" value="false"/>
I had to remove (Source Link):
<authorization>
<deny users="?" />
</authorization>
I know I may be late, and this is not directly for the OP's question. But if anyone in the future come here, one more check about AllowAnonymous and Authorize attribute is that, you have to check all child actions too.
For example, I had my Layout (which the Login page also use) that call 2 child actions for breadcrumbs and sidebar, and they did not have AllowAnonymous attribute (the Controller had Authorize attribute).
Hope this help.
In IIS, Select you website and check for Authentication, If you are using Forms Authentication then -
Set 'Windows Authentication' to 'Disabled' ,
Set 'Anonymous Authentication' to 'Enabled'
Set 'Forms Authentication' to 'Enabled'
ASP.Net MVC 5 template adds Microsoft.Owin and related libraries to the project. Since Owin infrastructure doesn't require Forms Authentication, the template also introduces the following key in web.config.
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
Presence of this key could be a reason for undesirable looping back to Login page. Commenting it may help fix the problem for some people.
I faced the same problem because my MVC project was configured for .Net 4.5 but I was using .Net 4.0 as my application pool in IIS. Switched it to .Net 4.5 application pool and the problem was fixed. I hope this helps some one else!
TL:DR? Do not call a protected web API (any web API which requires Authorization) from an authorization page such as ~/Account/Login (which, by itself, does NOT do this.). If you do you will enter into an infinite redirect loop on the server-side.
Cause
I found that the culprit was, indirectly, AccountController::Authorize and the fact that AccountController is decorated with [Authorize].
The root cause was Sammy() being called from HomeViewModel() (Line 6 of home.viewmodel.js), which was accessing a "protected web API". This was being done for /Account/Login, which resulted in /Account/Login redirecting to itself.
Confirmation
You can confirm this is the cause of your problem through several methods:
Decorate AccountController::Authorize with [AllowAnonymous]
Comment out the Sammy() calls made during viewmodel construction.
Solution
The solution was to only emit the app bundle (a.k.a "~/bundles/app") for views which already required authorization. To my knowledge /Account/ views are classic MVC-based views, and are not part of the app datamodel/viewmodel, but I had mistakenly moved the bundle Scripts.Render(#"~/bundles/app") call into _Layout.cshtml (causing protected web API calls to be made for all MVC views, including /Account/.)
in my case: in my _layout.cshtml, i use Html.Action to call Action from Authorize Controller: ex: Html.Action("Count", "Product") -> loop error
fix: decorate by [AllowAnonymous] attribute in that Action (or remove these Html helper from _layout)
I just dealt with this issue for hours on end.
For me, it was in the Startup.Auth.cs file.
This code, when commented out, stopped the redirect loop.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
Please be aware that this is potentially harmful advice, it's rarely a good idea to modify an applicationhost config file directly, there are usually tools that will do this for you, safely (for example, from within Visual Studio.) Before proceeding, be sure to create a backup copy of this file in the event your IIS Express becomes trashed.
To fix this problem, I took the default IIS configuration file located here :
C:\Windows\System32\inetsrv\config\applicationHost.config
To my document
%userprofile%\documents\iisexpress\config\applicationhost.config
And it worked.
This was because I had some Windows Authentification set and not the anonymous account.
Make sure you have no actions in pipeline that have authorize attribute.
In my case, my layout had navigation menu controller which was missing allowAnonymous attribute.
I solved the same problem thanks to this accepted answer: ASP.NET Login Redirect Loop when user not in role.
It is possible that the controller containing Login action is decorated with an AuthorizeAttribute (even a custom one) while the login action is not decorated with AllowAnonymous attribute. Removing AuthorizeAttribute from the controller and adding AllowAnonymous to login action may be a possible solution.
These answers are more or less pieces of the same puzzle; I'll try to put everything in one place.
Problem that OP described hit my application the moment I implemented the OWIN pipeline and AspNET Identity.
So let's see how to fix it...
OWIN Startup
I guess you need it, because if you don't, then you don't need authentication, and I guess you do.
Except it you're using some old-style authentication, and I guess you don't.
So, don't remove either the OWIN startup attribute...
[assembly: OwinStartupAttribute(typeof(YourApp.Probably_App_Start.SomethingLikeAuthConfig))]
...or the configuration line...
<add key="owin:AppStartup" value="YourApp.Probably_App_Start.SomethingLikeAuthConfig" />
Access restriction on controllers
Now we cleared this up, you need the authentication. This means either each of your controller needs the [Authorize] attribute, or you can do the same to all controllers in one place by registering the thing globally (e.g. in RegisterGlobalFilters(), add line filter.Add(new AuthorizeAttribute())).
In the former case (when securing each controller separately) skip this part, just go to the next one.
In the latter case all of your controllers will be secured against unauthorized acces, so you need an entry point for that authorization - unprotected Login() action.
Just add...
[AllowAnonymous]
...and you should be good.
OWIN cookie configuration
When your user logs in, his browser stores encrypted (hopefully!) cookie in order to simplify things for the system. So, you need cookie - don't delete the line that says UseCookieAuthentication.
What you really have to do is turn off the IIS integrated authentication mechanism for your web application. This means switching off Windows Authentication (Disabled) and enable letting any user in, at least as long as IIS Express is now concerned, by setting Anonymous Authentication (Enabled).
When you start your web site, this will in turn copy these settings into IIS Express configuration (applicationhost.config), and there you should see these two lines:
<windowsAuthentication enabled="false" />
<anonymousAuthentication enabled="true" />
You might have the authorization config in your web.config that says deny users="?". It means the authorization subsystem is instructed to prevent anonymous users from entering.
With OWIN, this still works as designed. You either have to remove this, or make your anonymous user able to access the Login page by using something like...
<location path="Account/Login">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
HTH
I had similar issues where it was in an infinite loop when calling back to the website locally. It turns out that when debugging locally it was redirecting the ports. I updated port numbers in the project properties screen but left the Azure definition the same in the cloud project and everything started to work as expected.
I had the same issue with my Asp.Net MVC 4 project. I resolved it by going to Startup.cs and commenting out the line for ConfigureAuth(app)
public void Configuration(IAppBuilder app)
{
//ConfigureAuth(app);
}
I also made sure that I had Windows Authentication enabled in IIS for my project, and all other authentication options disabled.
For me, this turned out to be caused by my LoginViewModel containing references to translation resources files, apparently being protected by authentication. I removed those references, and the problem was solved.
For me, removing the following block fixed it:
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
Assume
<authentication mode="None" />
in my case it was a very wired problem , i decorated the home controller by non existent role. so it causes a redirection loop.
Go to to your applicationhost.config file and set anonymousauthentication = "true"
<authentication>
<anonymousAuthentication enabled="true" userName="" />
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>

How to create generic web.config file for different web servers in .net web application?

I want to create a generic web.config file for different web servers in VB.NET. So, depending on the server configuration requirements, applications can retrieve all values from that generic configuration file.
Is this possible? How would I do this?
This is just a random idea, it may not fit your needs though. You could create a configuration section for each server named by the name of the server. Create a helper class for reading configuration values that checks for any values in the section named after the server's name first, if it doesn't exist read it from a default configuration section.
I'm still not sure if this would be a wise decision, its just an option.
Technically, there's the machine.config which includes settings that apply to the entire machine.
web.config files can override some settings from it.
For everything that stays the same, use the a single web.config.
For everything that changes, use a reference to an external file.
<configuration>
<appSettings file="ExternalWeb.config">
<add key="MyKey" value="MyValue" />
</appSettings>
...
</configuration>
http://www.devx.com/vb2themax/Tip/18880
This way when things change in the main web.config, few things must be updated.
You may also consider using templates and code generation techniques to generate a web.config for each server.
How about a "mode" appsetting key/value. This "mode" can be set to "dev", "testing", "prod", etc. Then, set the mode of the current configuration file and prefix all the settings that would change with the mode.
Example:
<add key="mode" value="test" /> <!-- possible values: dev, test, prod -->
<add key="dev.dbconnstr" value="data source=DB;userid=ABC;password=DEF" />
<add key="test.dbconnstr" value="data source=DB;userid=ABC;password=DEF" />
<add key="prod.dbconnstr" value="data source=DB;userid=###;password=###" />
Then, use a configuration class to read the setting depending on the mode.
Example:
mode = ConfigurationManager.AppSettings("mode");
CongifurationManager.AppSettings(mode + ".dbconnstr");
Doing it this way, you can have the same config file deployed to all servers, and never have to worry about tweaking each server (except of course updating the "mode" value when deploying). I would also recommend not saving the production credentials in the other configuration files, instead replace it with a placeholder.
You could create a deployment script in something like nant which loads in a web.config containing placeholders for the configuration options. This could then replace the placeholders for the appropriate environments.

How do you modify the web.config appSettings at runtime?

I am confused on how to modify the web.config appSettings values at runtime. For example, I have this appSettings section:
<appSettings>
<add key="productspagedesc" value="TODO: Edit this default message" />
<add key="servicespagedesc" value="TODO: Edit this default message" />
<add key="contactspagedesc" value="TODO: Edit this default message" />
<add key="aboutpagedesc" value="TODO: Edit this default message" />
<add key="homepagedesc" value="TODO: Edit this default message" />
</appSettings>
Let's say, I want to modify the "homepagedesc" key at runtime. I tried ConfigurationManager and WebConfigurationManager static classes, but the settings are "read-only". How do I modify appSettings values at runtime?
UPDATE:
Ok, so here I am 5 years later. I would like to point out that experience has told me, we should not put any configuration that intentionally is editable at runtime in the web.config file but instead we should put it in a separate XML file as what one of the users commented below. This will not require any of edit of web.config file to restart the App which will result with angry users calling you.
You need to use WebConfigurationManager.OpenWebConfiguration():
For Example:
Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()
I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.
Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).
Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.
Changing the web.config generally causes an application restart.
If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an xml file with the editable settings.
And if you want to avoid the restart of the application, you can move out the appSettings section:
<appSettings configSource="Config\appSettings.config"/>
to a separate file. And in combination with ConfigurationSaveMode.Minimal
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);
you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.
2012
This is a better solution for this scenario (tested With Visual Studio 2008):
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();
Update 2018 =>
Tested in vs 2015 - Asp.net MVC5
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();
if u need to checking element exist, use this code:
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();
I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.
I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.
The project goals were very simple;
get ASP.NET to communicate with ZooKeeper
in Global.asax, Application_Start - pull web.config settings from ZooKeeper.
Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;
ConfigurationManager.AppSettings.Add(key_name, data_value)
That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.
After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.
With a little trial and error, I found the following code would do exactly what I wanted;
ConfigurationManager.AppSettings.Set(key_name, data_value)
Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.
In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;
appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True
With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.
This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.
I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.
Who likes directly to the point,
In your Config
<appSettings>
<add key="Conf_id" value="71" />
</appSettings>
in your code(c#)
///SET
ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
///GET
string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();
Try This:
using System;
using System.Configuration;
using System.Web.Configuration;
namespace SampleApplication.WebConfig
{
public partial class webConfigFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
//Save the Modified settings of AppSettings.
webConfigApp.Save();
}
}
}

Resources