Threads I searched
ConfigurationManager.AppSettings count 0
Reading settings from app.config or web.config in .NET
ConfigurationManager.AppSettings is empty?
WPF configurationmanager.appsettings collection is empty
My application is a .NET Core 3.1 app so I added the library System.Configuration.ConfigurationManager via NuGet to my project. My root folder contains a Web.Config with the following contents
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" />
<httpRuntime />
</system.web>
<appSettings>
<!-- Folder of LogParser job-configurations -->
<add key="JobFolder" value="App_Data/jobs"/>
<!-- Background task execution interval in seconds -->
<add key="Interval" value="5"/>
<!-- Message offset in seconds. Reads older messages to circumvent log4net timestamp bug -->
<add key="Offset" value="7200"/>
<!-- Caching duration for hash MemoryCache in seconds. Default is 604800 (7 days) -->
<add key="Caching" value="604800"/>
</appSettings>
</configuration>
However, when I access ConfigurationManager.AppSettings[key] it's always empty. Also, Configurationmanager.AppSettings.AllKeys is empty and the count is 0, as if it's not being parsed.
Any ideas?
I'd like to add for anyone who comes here doesn't have the option to use the appsettings.json....
For me this problem manifest itself inside a UnitTest project. ConfigurationManager expects a file named ASSEMBLYNAME.dll.config, but the Unit Tests in .net core run under the name "testhost" so it looks for testhost.dll.config. Therefore you need to rename the generated config file to match what ConfigurationManager is looking for.
In your csproj file, add a build step like such...
<Target Name="CopyAppConfig" AfterTargets="Build" DependsOnTargets="Build">
<CreateItem Include="$(OutputPath)$(AssemblyName).dll.config">
<Output TaskParameter="Include" ItemName="FilesToCopy"/>
</CreateItem>
<Copy SourceFiles="#(FilesToCopy)" DestinationFiles="$(OutputPath)testhost.dll.config" />
</Target>
Solution came from
https://github.com/microsoft/testfx/issues/348
Okay, https://stackoverflow.com/users/392957/tony-abrams pointed me in the right direction.
So basically, I need an appsettings.json file (even if the Internet told me otherwise) and I defined it like this
{
"JobFolder": "App_Data/jobs",
"Interval": 5,
"Offset": 7200,
"Caching": 604800
}
Then, in the class where I need this I added a new constructor argument IConfiguration configuration which is already registered in the DI container, so no further action needed there.
Then, when I want to access the value, I can simply do _configuration.GetValue<string>("JobFolder") and have the value.
Thank you.
I ran into this issue when migrating asp app from .net 4.x to .net core 3.1. To preserve functionality relying on ConfigurationManager I also installed nuget package System.Configuration.ConfigurationManager, but both ConnectionStrings and AppSettings were empty.
At the moment I cannot use appsettings.json, so I had to move my settings from web.config to app.config. It seems like
.net core version of ConfigurationManager works only with app.config.
Related
I am using ConfigurationManager.AppSettings["someKey"] to retrieve values from app.config appSettings
<appSettings>
<add key="someKey" value="value" />
...
However, when I use this in my unit tests, the ConfigurationManager.AppSettings collection is empty.
This happens only when I run the tests from JetBrains Rider IDE!
Running them from Visual Studio (even with ReSharper runner) works perfectly fine and values are loaded.
It is a .Net 5 project using XUnit framework.
What is going on with Rider here?
First make sure the app.config is in the correct format. since you want to reference ConfigurationManager.AppSettings["someKey"]
the app.config should be structed this way
<configuration>
<appSettings>
<add key="someKey" value="value" />
</appSettings>
</configuration>
copy the app.config to the project-folder\bin\Debug\net5.0 and rename in a way that is understood by the IDE which can be achieved through adding the following lines in project file
<Target Name="CopyCustomContent" AfterTargets="AfterBuild" >
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)/ReSharperTestRunner.dll.config" />
<Target/>
Hope this helps!!
My OWIN web service runs beautifully in Visual Studio 2013, but when I publish it to a real IIS site, it acts as if the Configuration method in the startup class has not been run. I can do "normal" things like browse to the app and see the directory structure, but nothing that was supposedly set up with the IAppBuilder is functional. For example, I get a 404.0 error when I browse to a URL that was set up in Startup to issue an OAuth2 bearer token. It's as if Startup.Configuration(IAppBuilder app) was never run.
I'm using the [assembly: OwinStartup(typeof(MyNamespacedStartupClass))] attribute to designate the startup class.
I've used NuGet to get both Microsoft.Owin.Host.SystemWeb and Microsoft.Owin.Diagnostics per instructions I've seen, but that doesn't make a difference.
What more do I have to do?
Make sure your app pool is in v4.0 integrated mode.
Make sure you have bin placed Microsoft.Owin.Host.SystemWeb (I see you have installed it) - Just make sure its also in the bin folder.
This article will have more information on how an OWIN middleware runs on Integrated pipeline.
I also had to add an extra setting to my web.config
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
From: https://katanaproject.codeplex.com/wikipage?title=Static%20Files%20on%20IIS
IIS has a native static file module that is optimize to skip other
portions of the pipeline if it sees file paths that do not match other
handlers (e.g. not aspx). This means that the directory browser
middleware is likely to work, but then the static file middleware may
be bypassed in favor of the native static file module.
This tells IIS not to skip the managed Asp.Net modules even if the
native static file module thinks it has a match.
It also describes another step, but this was not needed for me:
Also, add the following stage marker AFTER your static file middleware
(in namespace Microsoft.Owin.Extensions):
app.UseStageMarker(PipelineStage.MapHandler);
Probably the reason if you upgraded at some point from an older MVC:
Make sure you don't have
<add key="owin:AutomaticAppStartup" value="false" />
in your web.config. It will suppress calling the startup
Instead change it to this
<add key="owin:AutomaticAppStartup" value="true" />
Somewhere along the line - when I upgraded to MVC 5 this got added (actually almost ironically it was a year ago tomorrow) and I never even knew what owin was until today when I tried to use it.
I also faced same problems when I migrated my already running MVC5 site to a new server. It gave me nightmares, just to recap I had to do all this to get it working
Add [assembly: OwinStartupAttribute(typeof([YourAssemblyName].Startup))] this to the Startup class (after the using statements and before the namespace declaration)
Add these keys to the <appSettings> section of web.config
<add key="owin:AppStartup" value="[NamespaceForYourStartUpClass].Startup, [YourAssemblyName]" />
<add key="owin:AutomaticAppStartup" value="true" />
And lastly as suggested by Martijn Evens add the following to <system.webserver> section in web.config
<modules runAllManagedModulesForAllRequests="true" />
For those who deal with legacy and (or) have migrated versions. Check windows "Roles and features", find what version of ASP.net is installed, and use exactly the same version in web.config for targetFramework, for example in my case it was 4.6 not 4.8, so
<system.web>
<httpRuntime targetFramework="4.6" requestValidationMode="2.0" maxQueryStringLength="2097151" />
<compilation targetFramework="4.6" optimizeCompilations="true">
As it stands, right now when I deploy my web application I always go into my web.config file to change the server name etc from the connection string manually before deploying the application. Is there an easier way to deploy a web app without having to always change the server in the connection string?
Thanks
Use a transform Web.config When Deploying a Web Application Project:
How to: Transform Web.config When Deploying a Web Application Project
Web.config Transformation Syntax for Web Project Deployment Using Visual Studio
It depends on how you are deploying your web app, but one common way to do it is to use web.config transforms
http://msdn.microsoft.com/en-us/library/dd465326%28v=vs.110%29.aspx
we use WIX installer exactly for this purpose.
It can be customized, like in my case, to select DEV, QA or PROD env while installation.
Best thing is it uses underlying MSI installation framework, if thats the right word here.
Assuming you only need to change the connection string for just one specific Web Deploy then you can do that with a transformation as others have said. The following should show exactly what you need to do.
In Solution Explorer expand the Properties node to get the PublishProperties as in the following.
Right-click on the Web Deploy profile and select Add Config Transform as shown in the following.
You will get a Web.project - Web Deploy.config file in the Web Config node. The initial contents will be the following.
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on using web.config transformation visit https://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<!--
In the example below, the "Replace" transform will replace the entire
<customErrors> section of your web.config file.
Note that because there is only one customErrors section under the
<system.web> node, there is no need to use the "xdt:Locator" attribute.
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
Change the sample to the following or add the following.
<connectionStrings>
<add name="csname"
connectionString="yourotherconnectionstring"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
Where csname is the name in the Web.config of your connection string that you need to replace in the deployment.
There are many other transformations possible but if you only need to change the connection string for a specific Web Deploy then that should be the most straight forward. It is saying that you want to search for the connection string that has the specified name and then change the connection string value during the deployment.
I'm using .NET MVC
I have about 10 properties I want to store in a configuration file (.config etc.), related to environment/deployment stuff, + other things for quick changes without doing dLL deploys.
I'm using Team foundation service for CI builds etc, and my web.config is obviously under version-contrl.
What I'd like to do is have a settings.config (that's not in version control) file to store these, am I able to do this?
Or does it need to be in web.config?
To answer the title question, yes you can store settings in a separate config file, to do so you need to define the configSource property of appSettings element
E.g.
<appSettings configSource="settings.config" />
and in the settings.config file
<?xml version="1.0" encoding="UTF-8"?>
<appSettings>
<add key="settingKey" value="environmentValue" />
</appSettings>
However, for the sake of environment specific settings, you may want to look at config transforms. Setting up a transform config for each environment then deploying to that environment with the specified build configuration.
E.g. Web.Dev.config (provided you have setup a 'Dev' build configuration)
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="settingKey"
value="devEnvironmentValue"
xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>
</configuration>
More details of build configuration and config transforms here: http://msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx
Or you could take advantage of TFS features and parameterize the environment variables, I don't have a lot of experience with this, but the following should help: http://ig.obsglobal.com/2013/02/tfs-and-continuous-deployment-part-4-parameterized-deployments/
I have a .net github project that is basically a wrapper around a web API. In the test project, I am calling to the API using an API key. I need to keep this key private, how do I accomplish this in a visual studio project?
In some other projects, like python, I can have git ignore the file (config.py) and use something like config.example.py. But in visual studio's case, the project will not compile because of the missing file Config.cs. What is the proper way to solve this? I'm thinking of using this same method of ignoring the file and have them execute a build script that should rename Config.example.cs to Config.cs?
This is the perfect for .config files. Depending on whether its a web or console application, you will have a web.config or app.config file in your project.
You can use the appSettings section to store your API key.
To make things even easier, you can actually have this section read from another file, ie: specialappsettings.config and then just ignore that single file from your repository.
Modify your web.config (or app.config):
<configuration>
<appSettings file="specialappsettings.config">
</appSettings>
<system.web>
<!-- standard web settings go here -->
</system.web>
</configuration>
Create a new specialappsettings.config file:
<appSettings>
<add key="APIKey" value="YourApiKeyValue" />
<add key="AnotherKey" value="AnotherValue" />
</appSettings>
This can be accessed in your code via:
var apiKey = ConfigurationManager.AppSettings["APIKey"];
Notes:
You can keep your settings within the original web.config file as
well but this lets you ignore just the specific settings file from
your git repository without affecting the rest of the project's
necessary configuration details.
The same "key" can be saved in
either file however the external file will override the original
web.config file value.
You are probably looking for the App.config file for a project. It will be copied to <application>.exe.config when you compile it. Users can edit that config file as needed.
In that config file, you can add your API keys:
<configuration>
<appSettings>
<add key="APIKey" value="12345"/>
</appSettings>
</configuration>
Then you can access it from your code using ConfigurationManager.AppSettings:
string apiKey = ConfigurationManager.AppSettings["APIKey"];
One option is to use .config files instead of having secret keys hardcoded in sources.
More info Using Settings in C# and step-by-step guide
<configuration>
<appSettings>
<add key="SecretKey" value="0" />
</appSettings>
</configuration>
var secretKey = ConfigurationManager.AppSettings.Get("SecretKey");
Perhaps you can store the key outside of the Config.cs file and load it at run time.
Bonus, other people using your code won't have to recompile the project to change to their API key.