Read a web.config file in a virtual directory - asp.net

I have an ASP.NET application (Root Application) that has a virtual directory set up to another ASP.NET application (Virtual Application). How can I make the Virtual Application read values from the Root Application's web.config file? I was looking at the WebConfigurationManager.OpenWebConfiguration() class, but I'm unsure how how to tell it to go up one level from the root. For example, I would tell it to go to ~/web.config to get the the Virtual Application's web.config file, but I need it to go up one more level to the Root Application's file structure. Is this even the correct approach?
Any help would be greatly appreciated!!

You can use the ExeConfigurationFileMap class with ConfigurationManager, like:
string configFile = new FileInfo(Server.MapPath("/Web.config")).Directory.Parent.FullName + "\\Web.config";
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = configFile;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
Response.Write(config.AppSettings.Settings["Test"].Value);

IIS does have programmatic access to its configuration data (which is documented on MSDN and/or Technet). This will be the only supported route (i.e. will continue to work across IIS versions).
Otherwise you can hack a solution (both of these will require higher than usual rights for the process):
Parse the output from appcmd.exe:
E.g. here:
> C:\Windows\system32\inetsrv\appcmd.exe list vdir
VDIR "Default Web Site/" (physicalPath:E:\Dev\weblocal\XYZ)
VDIR "Default Web Site/DevRoot/TestWebClient" (physicalPath:E:\Dev\Tests\ClientSideWeb)
VDIR "Default Web Site/Home" (physicalPath:E:\Data\Homepages)
Read the configuration directly from C:\Windows\System32\inetsrv\config.

I think you will find that your desired behavior is in fact the default behavior.
web.config settings cascade down. Your app will look up to the next hierarchical web.config if it can't find the value.
This would allow you to just look up via AppSettings etc. for most cases.
I'm not sure what happens if you really need to direct access to the file as opposed to the various config api access methods.
I have a setup like this right now using IIS7 with multiple virtual apps configured.

I tried HectorMac's suggestion again and it still doesn't work for me. As a result I am going to seek an alternative to storing my value in the web.config file.

Related

Confused on what is the correct procedure on storing passwords in Web.config for Azure deployment

I've had a very frustrating experience on putting an MVC 5 app on Azure. I have been reading the following page: http://www.asp.net/identity/overview/features-api/best-practices-for-deploying-passwords-and-other-sensitive-data-to-aspnet-and-azure
But what I haven't managed to put in my head is the following:
Security Warning: Do not add your secrets .config file to your project or check it into source control. By default, Visual Studio sets the Build Action to Content, which means the file is deployed. For more information see Why don't all of the files in my project folder get deployed? Although you can use any extension for the secrets .config file, it's best to keep it .config, as config files are not served by IIS. Notice also that the AppSettingsSecrets.config file is two directory levels up from the web.config file, so it's completely out of the solution directory. By moving the file out of the solution directory, "git add *" won't add it to your repository.
And:
Security Warning: Unlike the AppSettingsSecrets.config file, the external connection strings file must be in the same directory as the root web.config file, so you'll have to take precautions to ensure you don't check it into your source repository.
The problem is the following: When I upload the Web.config file with the external files without being included I get hit by "The System cannot find the file specified", so for it to go away I must include the .config files defeating the purpose of Microsoft's post.
I really really really do not understand. I have added the connectionStrings and appSetting's keys in Azure's portal. What is the correct and secured way of putting my passwords and secrets online? What am I missing? Is it because I'm running in Debug mode?
According to this:
How can I secure passwords stored inside web.config?
There is nothing to worry about accessing the Web.config file...
But that just defies Microsoft's post.
Thanks.
I find the following technique to be the easiest way to do this.
Instead of putting the deployment values of these settings into the web.config, I keep the test values in there instead. I then put the deployment values into the Application Settings section of the Azure Website via the Azure Portal:
When the website runs, these settings will take precedence over what is in the web.config. This helps me avoid externalized files, allows me to keep sane development configuration that the team can share, and makes deployment very easy.
The best way is to set your secrets in the Connection Strings section of the portal. Any values set there will override values you specify in your web.config file.
This way they are only exposed to people who have admin access over the site itself. Having full access to the source won't even be enough to get the secret values.
More details here

Modifying Root Web.config in code

I would like to store some meta-information about a given site instance that can (a) be managed by that site instance and (b) persist clobbering of Web.config file.
The site will run in multiple environments (dev,testing,staging and production) and each environment can have different values for this metadata.
Note: All environments are running IIS 7.0+
The Root Web.config seems very appealing, as it is certainly outside of the website. Therefore, both files and databases can be changed while maintaining the metadata. I have seen how to modify the appSettings of the Web.config stored in the website, but is it possible to similarly modify the appSettings in the Root Web.config (Specifically within the proper directive)?
If you have other suggestions of approaching this problem, I would be very happy to hear them. Thank you!
would not use web.config for runtime modifications, that will cause the application to recycle, perhaps some other form of configuration file like app.config
if my assumption is incorrect and the web.config will not be edited after the application is started, then you can use WebConfigurationManager to access the file sections
Yes you can modufy the app settings within your web.config Just use the WebConfigurationManager class in the System.Web.Configuration namespace to create a Configuration object. This object could then be used to read and write changes to the web.config file.
You could then create your own "keys" or attributes that could be read as needed.
Depending upon what your attributes represent or if they need to be picked up by multiple environmnets from that server I would also look into making the modifications within the machine.config file as then those settings would apply to the enter machine and thereby picked up by multiple environments( if you are hosting multiple webapps from the server). This could save you time in modifying multiple web.config files and narrorw the storage or the metadata to one location vs. multiple config files in certain situations.

How to conditionally return web.config entry

How do I return web.config entry conditionally.
I.E: If the web.config folder is 'C:\inetpub\www\myTestSite' then return 'connectionString' TestDB
else return 'ProdDB'
You can try something like this:
string conn;
if (Server.MapPath("~/web.config").StartsWith(#"C:\inetpub\www\myTestSite"))
conn = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
else
conn = ConfigurationManager.ConnectionStrings["ProdDB"].ConnectionString;
Although I would recommend a different approach, either by using separate config files for your sites or by using a more sophisticated method of testing where your code is located. What I do is put a key in appSettings in the machine.config file for my development machine, as well as my test, and production web servers so that my application knows what environment it is running on. I use the value of that appSetting to determine which connection string to use.
It is much better to use different config files for the different wnvironments.
You can have the following in your web.config file:
<connectionStrings configSource="SiteSettings\connectionStrings.config"/>
where the configSource is path relative to the path of the web.config file. Then you can easily create 4 different connectionStrings.config files in your project: connectionStrings.config.dev, connectionStrings.config.test, connectionStrings.config.staging, connectionStrings.config.prod. With that set up you can configure your build process to automatically choose the right connectionStrings.config file for the right environment. This way maintenance will be a lot easier.
ScottGu has an article describing this method. And one more article about Customizing web.config for different environments which you may find helpful.

Multiple Web.Config files in ASP.NET web application

I have an ASP.NET web application where i am having multiple subrirectories in the root folder.in my root web.config, i have sessionMode as "StateServer" . So in one page of my subdirectory, i am not able to do serialization. If i change the SessionMode method to "InProc" , it will work fine. I want to maintain the web.config file in the root directory as it is.So i am planning about having another web.config file in sub directory.Can anyone tell me how to do this ?
Thanks in advance
While you can have a Web.config in every subdirectory not all settings are allowed at all levels.
And SessionMode is one setting that can only be made in the application-root.
You can just place a new web.config file in the sub-directory and ASP.NET will override any settings you change in that directory.
If you mark the class that is being put in the Session with the [Serializable] attribute, it can usually be used in an StateServer setup.
Just put another web.config in the subdirectory. ASP.NET allows for that, and I have several areas on my website where the web.config contains values specifically for that "application" specifically.
That said:
1) Are you sure it's a good idea to maintain state in two different ways? It would probably be better to figure out how to make your session state serializable or get rid of using session state altogether.
2) All those web.config files can get tough to maintain if you're not careful about what values you put in each.

ASP.NET: external custom config file in a virtual directory - how to?

I know that there at least two approaches to leverage the web.config file:
using the configSource attribute which was introduced in .NET 2.0 - here is a good blog entry about it.
The file attribute of the appSettings tag which lets you point to an external file with a relative path. Described in the MSDN documentation on the appSettings element.
Now, my problem is that both approaches work well only for physical paths. But I need to address a config file which is in a virtual directory.
Which other method could I use to put my config resources in a virtual directory?
Note: I want to do it this way, because I have multiple instances of my web application on the same server (and that on many servers). To keep deployment easy and clean, I want to keep one directory for all the files (aspx, ascx, images, css, js etc.) and point the web apps in IIS for different customers (=domains, https etc.) to this single directory. In every IIS web I would have a virtual directory called "custom" which points to a different folder for each web.
Update: I'd like to point out that this virtual directory "custom" is not suited to contain an inherited web.config - that web.config would be valid only for the custom folder which doesn't contain aspx/ascx files.
I have the same scenario and after reading you post I realised that asp.net won't let you do this for various security reasons.
Therefore I turned to the OS to find an equivalent to the Linux soft link function which in turn led me to the Junction utility from sysinternals. This can create a directory that is actually any other directory on that volume and asp.net can't tell the difference and so happy loads the config sections that are not actually in a subdirectory of you website. Works for me :)
Virtual Directories can be set as applications, and you can just place another web.config there.
It will inherit any changes from the parent config, and you can add custom settings in it.
I was looking to do the same thing but it did not work, so I decided to do the opposite, as you know the web.config can be inherited, so I pointed IIS to a folder containing the client config (connection string, file path etc) files and the website files i put them on a virtual directory with the rest of the webconfig (where it load dll and other application files needed)
So basically i can use the website files to multple clients and the clients with their own Database connection string and other specific client settings.

Resources