How to override web.config values in custom section in Azure Web App? - azure

It is possible in Azure Web App to override web.config AppSettings section easily. E.g. if I have the following web.config:
<appSettings>
<add key="AllowedCORSOrigin" value="http://localhost:26674"/>
</appSettings>
I can override it in the app settings UI in the portal like that:
I have also a custom section in the web.config:
<AdWordsApi>
<add key="OAuth2RefreshToken" value="TOKEN" />
</AdWordsApi>
Is it possible to override it somehow as well? I have tried AdWordsApi.OAuth2RefreshToken and AdWordsApi:OAuth2RefreshToken, but that does not work that easily.
P.S. It's interesting to know if it's possible with other custom sections like e.g if I want another authentication mode on the server.
<system.web>
<authentication mode="None" />
</system.web>

Short answer is that it is not possible.
The mechanism you describes only works with App Settings and Connection Strings. High level, the way it works is:
Your Azure App Settings become environment variables
At runtime, a special module sets those dynamically in the .NET config system. Note that the physical web.config is never modified.
But it would be hard to make such mechanism work on arbitrary config sections, as those could not be dynamically affected without modifying the physical file.

If you are using Visual Studio use web.config transformations to change configuration settings depending on whether you are running locally or deploying to Azure:
How to Transform Web.config
In simple terms you create one more more build configurations (typically Debug & Release). In your Visual Studio solution right-click on your existing web.config file and click "Add Config Transform", this will create a Web.Debug.Config and Web.Release.Config file which you can then customise with specific settings depending on the environment. Link this with your Azure build configuration and you can then have any combination of settings for local and remote deployment.

This is old but leaving this reference to how to use Azure Resource Manager to potentially solve this.

You can transform the values by the listed in VSTS by doing the following steps in App.Release.config:-
Add xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" in configuration section
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
</configuration>
Add xdt:Transform="Replace" in custom section like below
<AdWordsApi xdt:Transform="Replace">
<add key="OAuth2RefreshToken" value="TOKEN" />
</AdWordsApi>
Create variable token in the release pipeline e.g OAuth2RefreshToken
Then in file config use it as following
<AdWordsApi xdt:Transform="Replace">
<add key="OAuth2RefreshToken" value="#{OAuth2RefreshToken}#" />
</AdWordsApi>

If you are adding any in web.config --> Appsetting, you can overirde it in Azure App Service using variable prefix
Key Name: APPSETTING_AllowedCORSOrigin
Value: http://localhost:26674
https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#variable-prefixes

Related

what are all the locations in which connectionStrings can be defined for an iis site?

I'm trying to find all the locations in which a connectionString can be defined for an iis site (to write a script to extract them all).
I know it can be part of a web.config. I would like to have a complete list of files it can be configured in.
Does it make sense for it to be configured in the site code?
Which other configuration files can define a site's connectionStrings?
And a bonus question - how do I know the order of the files in which the connectionString is searched in ?
Thanks,
EDIT:
Additional info - all IIS sites are pure dotnet sites.
Also, specifying the general location of files, rather then file names, is also helpful.
E.g. - connectionStings can be located in external configuration files, whose location is defined at a in an appSettings element in the "%runtime install path%\config\machine.config" file.
Another option is to just link to the relevant docs.
My issue is that I haven't found anything conclusive.
As far as I know, there are several ways to configure connectionstring in ASP.NET applications.
Define it in code. This is the method used by many beginners. Because at this time they focus on code learning and logical understanding. But some people are accustomed to using it if the database is fixed, it does not need to be modified.
SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=mytest;Integrated Security=True");
Define it in web.config or App.config. The benefit of it is easy to modified connectionstring after publishing application. Developers can change web.config, no need to change code and deploy application again.
<connectionStrings>
<add name="mytest" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=mytest;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Using External Configuration Files. ConnectionString is stored in a independent file for example connections.config. The benefit of it is modifying an external configuration file does not cause an application restart.
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>
About list all connectionstrings, you can use ConnectionStringSettingsCollection. It can get a connection by name and provider name.
I found a pretty good source for the locations of the IIS dotnet Framework configuration files - https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc754617(v=ws.10)?redirectedfrom=MSDN#inheritance
You could define additional connectionStrings
In dotnet code.
In env.
In external config files.
For non-IIS scopes - such as user scopes and role scopes.
These 4 options are not specific to IIS.
I don't know where options (3) and (4) are defined, and I'm not sure if this list is complete. But by combing this list and the one in the doc, I think we have 99% coverage of defined connectionStrings.

Custom Functions not working for IIS hosted Office Excel add-in

We deployed Batching Custom functions project into IIS as hosted application. Task-pane is working fine with API. But when trying to invoke as custom functions facing issue
Error in loading custom functions
at the bottom of add-in. We developed using webpack.config.js but little confused when deploying on IIS for exact server running. So do we need to use express js to run separate port or directly shall we run only enough webpack.config.js file? Kindly confirm on this deployment process.
Also Taskpane related API's are able to fetch successfully but only facing issue with custom functions related API.
You may can check if custom function related files can be seen in your website hosted by IIS. You can have the url information in manifest file.
Would you please check whether you could access the JSON file by browsing to http:///custom-function.json? Would you please also check whether the mime type is correct? If the mime type is not correct, you may need to update the web.config, such as
<configuration>
<system.webServer>
<staticContent>
<remove fileExtension=".json"/>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
</configuration>
By the way, to make it work for Excel online, you also need to enable CORS access to the custom-function.json

Refer a connectionstring from web config in another config file

I am using NLog to write logs to my database,
I have created a file NLog.config which is writing logs to a text file as of now.
To write the logs to a database, I am following this tutorial.
However, the connectionstrings for diferrent environments can be only modified in Web.config. (I am using Azure App services). Is there any way I can refer the connection string from web.config in NLog.config.
TIA
If you not using ASP.NET Core (but "full" ASP.NET), you could use ${appsetting:name=..}
Install NLog.Extended with Nuget and use ${appsetting:name=..} in your config file.
e.g.
<target name="database"
type="Database"
connectionString="${appsetting:name=myConnectionString}" />
See also the ${appsetting} documentation
NB: It can only read <appSettings> and not <connectionStrings>

Override applicationSettings "MySite.Properties.Settings.MySetting" in Azure Website

I have a website (not web role) that I'm deploying to Azure, using the Basic tier. The web.config file has the following auto-generated section for website settings:
<applicationSettings>
<MySite.Web.Properties.Settings>
<setting name="MySetting" serializeAs="String">
<value>coolValue</value>
</setting>
</MySite.Web.Properties.Settings>
</applicationSettings>
I'm trying to override the value of MySetting in Azure's Web Apps -> MySite -> Configure -> app settings section. The idea being that the live website has a different value than the development version. I'm trying to avoid storing the live website's value in the web.config file (nor doing transforms).
I've tried the following values in the app settings section of the azure web app configuration section:
MySetting = somethingElse
MySite.Web.Properties.Settings.MySetting = somethingElse
Neither of these things worked. I like the new strongly-typed settings class in .NET, and don't really want to flatten the app settings out (using the old way).
Does anyone know how to override these types of settings in Azure?
Have you added the applicationSettings to the section group?
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Tools.Instrumentation.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
One alternative is to set the App Settings from the Azure Portal. Go to the Azure Portal->Navigate to your website->Settings->App Settings and set the key, value pair there.
All settings will show up as environment variables, so you can set different values for the same settings in your test and production environments.
See here for more info:
http://azure.microsoft.com/blog/2013/07/17/windows-azure-web-sites-how-application-strings-and-connection-strings-work/
I asked around Microsoft's support & could not get an answer for this issue as I wanted to do this too. Fortunately while trying to better understand Microsoft's Web Deploy I discovered how to do this.
First, you'll need to use an external config file instead of just adding them into the web.config file. In your web.config file replace the following:
<applicationSettings>
<MySite.Web.Properties.Settings>
<setting name="MySetting" serializeAs="String">
<value>coolValue</value>
</setting>
</MySite.Web.Properties.Settings>
</applicationSettings>
Use an external configuration file like this instead:
<applicationSettings>
<MySite.Web.Properties.Settings configSource="BusinessLogic.config" />
</applicationSettings>
Also in your web.config file you will need to add the following to your configSections:
<configSections>
<sectionGroup name="applicationSettings">
<section name="MySite.Web.Properties.Settings" />
</sectionGroup>
</configSections>
You can read the MSDN article for more on this if need be.
In your BusinessLogic.config file, located in your root with your web.config file you would add your settings:
<MySite.Web.Properties.Settings>
<setting name="SecretPassword" serializeAs="String">
<value>1234567890abc!##</value>
</setting>
</MyApplication.Properties.Settings>
Now manually add this same BusinessLogic.config file to your site on Azure with the settings you want it to have in Azure.
Finally open up your .csproj file and look for the following XML configuration:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
Within there you can exclude files from deployment by adding a line like this:
<ExcludeFilesFromDeployment>BusinessLogic.config</ExcludeFilesFromDeployment>
If you need to exclude more files, you can separate them with a semicolon.
Now in my case when I commit all these files to my git repository, Azure will automatically grab them & put them in a temporary file where it will build the project and then deploy it to the folder where the website lives. Upon deploying it will notice to ignore the BusinessLogic.config file and the file you manually placed in Azure will be used instead.

Config Error: This configuration section cannot be used at this path

I've encountered an error deploying a site to a server. When trying to load the home page, or access authentication on the new site in IIS, I get the error:
Config Error: This configuration section cannot be used at this path.
This happens when the section is locked at a parent level. Locking is
either by default (overrideModeDefault="Deny"), or set explicitly by a
location tag with overrideMode="Deny" or the legacy
allowOverride="false".
More detail can be found here, in Scenario 7 matches my hex error code.
The solution given on the linked site above is to set Allow for overrideModeDefault in the section mentioned in my error, in the applicationHost.config file. In my case, under Security in system.webServer. But if I look at the applicationHost.config on my local computer, where the site is properly deployed already, that section is set to Deny.
If this solution is correct, how is my local instance running just fine with the same web.config? According to my applicationHost.config, that section should be locked, but it's not. I'd prefer to not change the applicationHost.config file, because there are many other sites running on that server. Is there another solution?
I had the same problem. Don't remember where I found it on the web, but here is what I did:
Click "Start button"
in the search box, enter "Turn windows features on or off"
in the features window, Click: "Internet Information Services"
Click: "World Wide Web Services"
Click: "Application Development Features"
Check (enable) the features. I checked all but CGI.
btw, I'm using Windows 7. Many comments over the years have certified this works all the way up to Windows 10 and Server 2019, as well.
You could also use the IIS Manager to edit those settings.
Care of this Learn IIS article:
Using the Feature Delegation from the root of IIS:
You can then control each of machine-level read/write permissions, which will otherwise give you the overrideMode="Deny" errors.
For Windows Server 2012 and IIS 8, the procedure is similar.
The Web Server (IIS) and Application Server should be installed, and you should also have the optional Web Server (IIS) Support under Application Server.
Browse to “C:\Windows\System32\inetsrv\config” (you will need administrator rights here)
Open applicationHost.config
Note: In IISExpress and Visual Studio 2015 the applicationHost.config is stored in $(solutionDir).vs\config\applicationhost.config
Find the section that showed up in the “config source” part of the error message page. For me this has typically been “modules” or “handlers”
Change the overrideModeDefault attribute to be Allow
So the whole line now looks like:
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow" />
After saving the file, the page loaded up fine in my browser.
Warning:
Editing applicationHost.config on 64-bit Windows
You need to unlock handlers. This can be done using following cmd command:
%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers
Maybe another info for people that are getting this error on IIS 8, in my case was on Microsoft Server 2012 platform. I had spend couple of hours battling with other errors that bubbled up after executing appcmd. In the end I was able to fix it by removing Web Server Role and installing it again.
1. Open "Turn windows features on or off" by: WinKey+ R => "optionalfeatures" => OK
Enable those features under "Application Development Features"
Tested on Win 10 - But probably will work on other windows versions as well.
I ran these two commands from an elevated command prompt:
%windir%/system32/inetsrv/appcmd unlock config /section:anonymousAuthentication
%windir%/system32/inetsrv/appcmd unlock config /section:windowsAuthentication
As per my answer to this similar issue;
Try unlocking the relevant IIS configuration settings at server level, as follows:
Open IIS Manager
Select the server in the Connections pane
Open Configuration Editor in the main pane
In the Sections drop down, select the section to unlock, e.g. system.webServer > defaultPath
Click Unlock Attribute in the right pane
Repeat for any other settings which you need to unlock
Restart IIS (optional) - Select the server in the Conncetions pane, click Restart in the Actions pane
This Did the trick for me, for IIS 8 Windows server 2012 R2
Go to "Turn on Features"
Then go to all default setting , Next, Next, Next etc..
Then, select as shown below,
Then reset IIS (optional) but do it safer side.
This is an additional solution as its a generic problem everyone have different of problem and thus different solution. Cheers!
The best option is to Change Application Settings from the Custom Site Delegation
Open IIS and from the root select Feature Delegation and then select Application Settings and from the right sidebar select Read/Write
On Windows Server 2012 with IIS 8 I have solved this by enabling ASP.NET 4.5 feature:
and then following ken's answer.
To fix this open up the IIS Express applicationhost.config. This file is stored at C:\Users[your user name]\Documents\IISExpress\config\applicationhost.config
Update for VS2015+: config file location is $(solutionDir).vs\config\applicationhost.config
Look for the following lines
<section name="windowsAuthentication" overrideModeDefault="Deny" />
<section name="anonymousAuthentication" overrideModeDefault="Deny" />
<add name="WindowsAuthenticationModule" lockItem="true" />
<add name="AnonymousAuthenticationModule" lockItem="true" />
Change those lines to
<section name="windowsAuthentication" overrideModeDefault="Allow" />
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
<add name="WindowsAuthenticationModule" lockItem="false" />
<add name="AnonymousAuthenticationModule" lockItem="false" />
Save it and refresh Asp.net Page.
In our case on IIS 8 we found the error was produced when attempting to view Authentication" for a site, when:
The server Feature Delegation marked as "Authentication - Windows" = "Read Only"
The site had a web.config that explicitly referenced windows authentication; e.g.,
Marking the site Feature Delegation "Authentication - Windows" = "Read/Write", the error went away. It appears that, with the feature marked "Read Only", the web.config is not allowed to reference it at all even to disable it, as this apparently constitutes a write.
Seems that with IIS Express and VS 2015, there's a copy of the applicationHost.config file at $(solutionDir).vs\config\applicationhost.config so you'll need to make changes there. See this link: http://digitaldrummerj.me/iis-express-windows-authentication/
Make sure these lines are changed per below:
<section name="windowsAuthentication" overrideModeDefault="Allow" />
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
<add name="WindowsAuthenticationModule" lockItem="false" />
<add name="AnonymousAuthenticationModule" lockItem="false" />
In my case it was that on server was not enabled "HTTP Activation" under .NET Framework Features. So for Windows Server 2012 the solution which worked for me was:
Server Manager -> Add roles and features -> Features -> make sure that under .NET Framework of version you want to use is checked "HTTP Activation"
The Powershell way of enabling the features (Windows Server 2012 +) - trim as needed:
Install-WindowsFeature NET-Framework-Core
Install-WindowsFeature Web-Server -IncludeAllSubFeature
Install-WindowsFeature NET-Framework-Features -IncludeAllSubFeature
Install-WindowsFeature NET-Framework-45-ASPNET -IncludeAllSubFeature
Install-WindowsFeature Application-Server -IncludeAllSubFeature
Install-WindowsFeature MSMQ -IncludeAllSubFeature
Install-WindowsFeature WAS -IncludeAllSubFeature
The error says that the configuration section is locked at the parent level.
So it will not be directly 1 config file which will resolve the issue,
we need to go through the hierarchy of the config files to see the inheritance
Check the below link to go through the File hierarchy and inheritance in IIS
https://msdn.microsoft.com/en-us/library/ms178685.aspx
So you need to check for the app config settings in the below order
ApplicationHost.config in C:windows\system32\inetsrv\config. Change the overrideModeDefault attribute to be Allow.
ApplicationName.config or web.config in the applications directory
Web.config in the root directory.
Web.config in the specific website (My issue was found at this place).
Web.config of the root web (server's configuration)
machine.config of the machine (Root's web.config and machine.config can be found at - systemroot\MicrosoftNET\Framework\versionNumber\CONFIG\Machine.config)
Go carefully through all these configs in the order of 1 to 6 and you should find it.
I noticed one answer that was similar, but in my case I used the IIS Configured Editor to find the section I wanted to "unlock".
Then I copied the path and used it in my automation to unlock it prior to changing the sections I wanted to edit.
. "$($env:windir)\system32\inetsrv\appcmd" unlock config -section:system.webServer/security/authentication/windowsAuthentication
. "$($env:windir)\system32\inetsrv\appcmd" unlock config -section:system.webServer/security/authentication/anonymousAuthentication
I needed to change the SSL settings on a subfolder when i got this nice message. In my case following action helped me out.
Opened C:\Windows\System32\inetsrv\config\applicationHost.config
And changed the value from overrideModeDefault="Deny" to "Allow"
<sectionGroup name="system.webServer">
...
<sectionGroup name="security">
<section name="access" overrideModeDefault="Allow" />
</sectionGroup>
In my case, I got this error because I was operating on the wrong configuration file.
I was doing this:
Configuration config = serverManager.GetWebConfiguration(websiteName);
ConfigurationSection serverRuntimeSection = config.GetSection("system.webServer/serverRuntime");
serverRuntimeSection["alternateHostName"] = hostname;
instead of the correct code:
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection serverRuntimeSection = configApp.GetSection("system.webServer/serverRuntime", websiteName);
serverRuntimeSection["alternateHostName"] = hostname;
in other words, I was trying to operate on the website's web.config instead of the global file C:\Windows\System32\inetsrv\config\applicationHost.config, which has a section (or can have a section) for the website. The setting I was trying to change exists only in the applicationHost.config file.
In my case, it was something else.
When I loaded the solution in a new version of Visual Studio, VS apparently created a new project-specific applicationhost.config file:
MySolutionDir\.vs\config\applicationhost.config
It started using the settings from the new config, instead of my already customized global IIS Express settings.
(\Users\%USER%\Documents\IISExpress\config\applicationhost.config)
In my case this was the setting that needed to be set. Of course it could be something else for you:
<section name="ipSecurity" overrideModeDefault="Allow" />
Received this same issue after installing IIS 7 on Vista Home Premium. To correct error I changed the following values located in the applicationHost.config file located in Windows\system32\inetsrv.
Change all of the following values located in section -->
<div mce_keep="true"><section name="handlers" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"</div>
<div mce_keep="true"><section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"</div>
Can You try this:
Go to application path where you're getting deny error, right click
Properties->Security tab
In that, change the permissions and check the checkbox read and write. Then it will work without any error hopefully.
For Windows Server 2008 and IIS 7, the procedure is similar.
please refer to this:
http://msdn.microsoft.com/en-us/library/vstudio/bb763178(v=vs.100).aspx
in add role service, u will see "Application Development Features"
Check (enable) the features. I checked all.
In my case I was getting this error when attempting to update the authentication settings in IIS also in addition to browsing. I was able to remove this error by removing the authentication setting from the web.config itself. Removing a problematic configuration section may be less invasive and preferable in some cases than changing the server roles and features too much:
Section Removed:
<security>
<authentication>
<windowsAuthentication enabled="true" />
</authentication>
</security>
I had the similar issue, but I used the following powershell script which helped me to achieve above steps in on button click.
#Install IIS
Import-Module ServerManager
Add-WindowsFeature Web-Server, Web-Asp-Net45, Web-Mgmt-Console, Web-Scripting-Tools, NET-WCF-HTTP-Activation45, Web-Windows-Auth
the list of features can be added or removed based on the requirement.
I had an issue where I was putting in the override = "Allow" values (mentioned here already)......but on a x64 bit system.......my 32 notepad++ was phantom saving them. Switching to Notepad (which is a 64bit application on a x64 bit O/S) allowed me to save the settings.
See :
http://dpotter.net/technical/2009/11/editing-applicationhostconfig-on-64-bit-windows/
The relevant text:
One of the problems I’m running down required that I view and possibly edit applicationHost.config. This file is located at %SystemRoot%\System32\inetsrv\config. Seems simple enough. I was able to find it from the command line easily, but when I went to load it in my favorite editor (Notepad++) I got a file not found error. Turns out that the System32 folder is redirected for 32-bit applications to SysWOW64. There appears to be no way to view the System32 folder using a 32-bit app. Go figure.
Fortunately, 64-bit versions of Windows ship with a 64-bit version of Notepad. As much as I dislike it, at least it works.
I had the same issue.
Resolved it by enabling Application Server feature. Restarted iis
after that.
This worked for me
Also in IIS 8 you can solve this problem by changing the server to IIS Express. Goto debug->Properties
In the Web select the server as IIS Express from the dropdown and then rebuild the solution
To make a change at Application Level (Web.Config):
Please remove the Trust Level from the web.config:
Actually I was getting this error when I was trying to host my Website on the Hosting Server where I don't have control on their Server. Removing the above line from my Application web.config solved my issue.

Resources