问题
I appear to be having an odd issue where, in my global.asax in my Application_Start(), I have something that goes off to my database, gets all of my app settings from a name/value table, and then drops them into the application via Application.Add(name,value)
.
I have an 'application facade' in another project which is used by my service layers, data layers and so on in order to get settings I need to do various bits and pieces.
In my database, I have a couple of entries:
ConfigName | ConfigValue
WebServiceUsername | myUsername
WebServicePassword | myPassword
So in my method, I go off and get these values from the database, and put them into my application:
protected void GetApplicationSettings()
{
//Get all the config values out of the database, and then put them into the application keys...
var appConfigAttributes = ApplicationConfigurationService.GetAppConfigNames();
foreach (var appConfig in appConfigAttributes)
{
Application.Add(appConfig.ConfigName,appConfig.ConfigValue);
}
}
This is how I call the value from the application at a later time:
public static string WebServiceUsername
{
get { return WebConfigurationManager.AppSettings["WebServiceUsername"]; }
}
This is where things get weird.
If I call the application facade from my web layer with this:
<%= ApplicationFacade.WebServiceUsername %>
I get nothing back (yes, I have tried just ConfigurationManager in the get method!).
But this is the odd thing...
If I manually put an application key into my web.config file...
<appSettings>
<add key="putz" value="mash"/>
</appSettings>
And then build a similar property into my ApplicationFacade class as Putz, when I do the call in the view (<%= ApplicationFacade.Putz %>
) I get 'mash
' returned.
So, I know my ApplicationFacade is working correctly. So maybe it's my code in the application_start()?
Well, if I put this in my view <%=Application["WebServiceUsername"]%>
, myUsername
is returned.
What gives?!
Answer
ConfigurationManager.AppSettings.Set(appConfig.ConfigName,appConfig.ConfigValue);
回答1:
In Application_Start
when you refer to the Application
object this actually is an instance of HttpApplicationState which is used to hold application specific settings in memory and has nothing to do with key/value appSettings stored in web.config.
- When you use
WebConfigurationManager.AppSettings["someKey"]
this will return the value corresponding tosomeKey
in theappSettings
section of web.config. - When you use
Application["someKey"]
this will return a value cached in the application instance.
Both are completely unrelated and you can't expect to read values stored in Application["someKey"]
with WebConfigurationManager.AppSettings["someKey"]
.
来源:https://stackoverflow.com/questions/1582198/problems-retrieving-appsettings-added-during-application-start