Azure App Service - What modified my web.config? - azure-web-app-service

I have an ASP.NET Core website running from Kestrel. It is deployed to Azure App Service in production and another as staging.
I like to configure staging as "production-like" so I set ASPNETCORE_ENVIRONMENTNAME = Production in the Configuration blade of the App Service in the Azure portal. I could see from logs that the code was seeing the environment name as staging still.
It turns out <environmentVariable name="ASPNETCORE_ENVIRONMENTNAME" value="staging" /> is set in the web.config that's on the Azure instance!!
Now, I don't have this set in the web.config or any transforms in my codebase, and I don't use the web.config, in fact I want nothing to do with it or IIS.
My site is deployed via Azure Pipelines. I use environmentName as a build time variable but the YAML only uses it once, to concatenate some text to make up the resource group name.
I then ran dotnet deploy using the same command line as Azure Pipelines runs, but the web.config it writes into the final publish output folder doesn't contain the offending line either.
It was only a few weeks ago I rebuilt and redeployed all my Azure resources. It was all clean, and it's all scripted.
Where on Earth has it come from??!
I'm worried that if I remove it, one day, it'll magically just reappear. It smells very much like someone at Microsoft thought this automagic was a good idea.
Mind you, I've tried to remove it using the App Service Editor and Kudu but I'm not allowed!!
Your app is currently in read only mode because you are running from a package file. To make any changes, please update the content in your zip file and WEBSITE_RUN_FROM_PACKAGE app setting.
So if I'm not setting it, and I'm not allowed to change it, what do I do??
Update 1
I've downloaded the artifacts from Pipelines and the web.config has the setting in place.
The command run, according to the Pipelines log, was this.
dotnet publish --configuration Release --output D:\a\1\s/dotnet-publish-output
But when I run that myself, on my machine, it does not meddle with my web.config.

Wow. So whilst on the school run, it occurred to me that the value that the dotnet command writes into the web.config is correct. How does it know?
The only way it can know is from that environment variable I'm setting in Azure Pipelines and using in my YAML file azureResourceGroup: tz-$(environmentName).
And when I run it on my dev machine vs. running on the Azure build server, that environment variable is not set.
So I set environmentName in the environment on my dev machine before running dotnet publish and, hey presto! It screws up my web.config by adding an environment variable! Amazing.
> $env:environmentName = "undocumented-feature"
> dotnet publish --configuration Release --output C:\DATA\Published
...
> cat C:\DATA\Published\web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\MyWebsiteYeah.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="undocumented-feature" />
</environmentVariables>
</aspNetCore>
<security>
<requestFiltering>
<requestLimits maxUrl="32768" maxQueryString="262144"/>
</requestFiltering>
</security>
</system.webServer>
</location>
</configuration>
<!--ProjectGuid: 3E05D228-D9AF-4782-8E33-1F0E69992750-->
Isn't that dreadful.
So I solved the whole problem with my websites ignoring the variables set in the portal by changing the variable name in Pipelines to hostEnvironmentName.

Related

Update the apphostconfig file using appcmd

In an azure devops pipeline I try to run an appcmd command to modify the applicationhost.config file to set the ASPNETCORE_ENVIRONMENT variable
It works fine like this:
appcmd set config -section:system.applicationHost/applicationPools /+"[name='api.hostname.net'].environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='api.hostname.net']"
The problem is that this appcmd command works the first time, but as soon as the environment variable already exist it will throw an error message. Can I somehow ignore errors from appcmd? Or only add the environment variable if it does not exist from before?
I'm running appcmd commands using an azure devops IISWebAppManagementOnMachineGroup#0 task.
You can try to use XML transformation option in the IIS web deploy task. XML transformation supports transforming the configuration files (*.config files) and is based on the environment to which the web package will be deployed.
Transform file sample:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.webServer>
<aspNetCore ...>
<environmentVariables>
<environmentVariable xdt:Transform="Replace" xdt:Locator="Match(name)" name="ASPNETCORE_ENVIRONMENT" value="xxx" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
For details ,please refer to this document.
I have a similar requirement, and I have to scriptize these commands, so any UI-based method doesn't work for me. Provide my solution here.
I want to update an existed key named PasswordChangeEnabled which is located in appSettings section.
<appSettings>
<add key="PasswordChangeEnabled" value="false" />
</appSettings>
If I use set config with plus /+
appcmd set config "Site" /section:appSettings /+"[key='PasswordChangeEnabled',value='true']"
I will get an error message:
ERROR (Cannot add duplicate collection entry of type 'add' with unique
key attribute 'key' set to 'PasswordChangeEnabled')
So I changed the syntax to just modify the value:
appcmd set config "Site" /section:appSettings /"[key='PasswordChangeEnabled'].value:true"
This way worked for me.

How to fix error "ANCM In-Process Handler Load Failure"?

I'm setting up the first site in IIS on Windows Server 2016 Standard.
This is a NET Core 2.2 application. I cannot get the site to show.
I am getting this error:
HTTP Error 500.0 - ANCM In-Process Handler Load Failure
What can I change to clear this error and get my site to display?
My application is a dll.
I tested my application on the server through the Command Prompt with
dotnet ./MyApp.dll
it displays in the browser but only on the server itself with (localhost:5001/).
Using this method the site cannot be accessed from any other server.
When I set up the site through IIS, I get the In-Process error both on the server and from servers attempting to access the site.
At first I was receiving the Out-Process error. Something I read said to add this (hostingModel="inprocess") to my web.config
so I did but now I receive the In-Process error.
The site works fine when installed on my development server.
The Event Viewer shows this error for "IIS AspNetCore Module V2":
Failed to start application '/LM/W3SVC/2/ROOT', ErrorCode '0x8000ffff'.
This is my web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<customErrors mode="RemoteOnly"></customErrors>
<identity impersonate="false" password="****" userName="****" />
</system.web>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" hostingModel="inprocess" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
<environmentVariables />
</aspNetCore>
</system.webServer>
</configuration>
I had the same issue in .Net core 2.2. When I replace
web.config:
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
to
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
then it works fine.
Note: The same solution also works for .Net core 2.2 and other upper versions as well.
Open the .csproj file and under Project > PropertyGroup > AspNetCoreHostingModel, change the value “InProcess” to “OutOfProcess”.
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
Sometimes this is because multiple applications may be using same Application Pool
In such cases first application will work and other won't work
Solution is to create new application pool for each application.
I had the same error.
According to Microsoft(https://dotnet.microsoft.com/download/dotnet-core/current/runtime), We should install the 'ASP.NET Core Hosting Bundle' in our hosting server.
'The ASP.NET Core Hosting Bundle includes the .NET Core runtime and ASP.NET Core runtime. If installed on a machine with IIS it will also add the ASP.NET Core IIS Module'
After I did, The 'AspNetCoreModuleV2' installed on my server and everything works well. It didn't need to change your 'web.config' file.
For more info, in web.config, set
stdoutLogEnabled="true"
then check the logs folder. In my case it had nothing to do with project, publishing or hosting settings - it was my fault for not copying a file essential to my app. The error was simply "Could not find file "D:\Development\IIS Hosting Test\filename.ext"
For my particular issue it was the site permissions in IIS.
I edited the permissions to "Everyone" and it worked. I got the information from this page: https://github.com/aspnet/AspNetCore/issues/6111
I belive that IISExpress got messed up along the way.
Try the following:
'Clean Solution' from VS
Got to the solution folder and delete the .vs folder from there.
Build and run.
I faced with the same issue today, installing the following package on server is fixed the issue for me. If you have any previous version of Windows Hosting Bundle already installed on the server, you install the new one without restarting the server.
ASP.NET Core 3.1 Runtime (v3.1.11) - Windows Hosting Bundle
In my case updating .net core sdk works fine.
You can get this if you try to access the site using a IIS url but Visual Studio is setup to use IISExpress
See also
ASP.Net Core 1.0 RC2 : What are LAUNCHER_PATH and LAUNCHER_ARGS mentioned in web.config?
Long story short, the web.config is changed by Visual Studio when you switch between IIS and IISExpress. If you use an IIS url when it's setup to use IISExpress then the aspNetCore processPath will be wrong
Also, it's not uncommon to copy web.config files. You could get the same error if you don't change the processPath
I fixed this here Asp.Net Core Fails To Load - you need to specify that the program uses an in process or out of process model.
I changed my CreateWebHostBuilder to:
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = WebHost.CreateDefaultBuilder(args);
if (env == EnvironmentName.Staging || env == EnvironmentName.Production)
builder.UseIIS();
builder.UseStartup<Startup>();
return builder;
}
PS. I set ASPNETCORE_ENVIRONMENT in my .pubxml deployment profile by adding:
<PropertyGroup>
<EnvironmentName>Staging</EnvironmentName>
</PropertyGroup>
For me it was because I had ASPNETCORE_ENVIRONMENT environment variable being defined 2 times in my app - one in web.config and another - in applicationhost.config
In my case just adding MVC into Startup.cs Please follow into image. I am trying to add dependency injection then showing this problem. I think it will be helpful.
Follow this Image: https://i.stack.imgur.com/ykw8P.png
Delete the 'hosting Model ="in process"' section in web config.
Example:
<aspNetCore processPath="dotnet" arguments=".\WebAPICore.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
to
<aspNetCore processPath="dotnet" arguments=".\WebAPICore.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
I'm also getting "HTTP Error 500.0 - ANCM In-Process Handler Load Failure"
Except in my case...Everything was running great until I got the Blue Screen of Death.
I have a solution with two startup projects. One is an API (that comes up) and the other is a WebApp(which gets the error). Both are .NET Core 3.1..also VS2019.
First I tried setting a break point in Main() of program.cs...it never got this far.
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
On a hunch...I Looked at the NuGet packages installed.
I uninstalled and (re)installed
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation(3.1.6)
...and now its working again.
In case anyone else cannot find a solution to this here was my scenario:
I recently started a new project using .NET 5, and everything was working. Then I upgraded from Preview 5 to 7 and all of a sudden my IIS Express would no longer work. The fix for me was to simply repair Visual Studio:
.
This happened to me when I switched form debugging in IIS Express to IIS. I inspected Event Viewer > Application log, and found the following error there:
Executable was not found at '...\bin\Debug\netcoreapp3.1\%LAUNCHER_PATH%.exe'
I then found the solution to that in the following thread.
I basically needed to replace web.config entry with hard-coded name of the application:
<aspNetCore processPath="dotnet" arguments=".\ProjectName.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
I get that error when i try to get data from the ViewModel as List<> and my data is coming as IEnumerable format.
Before u guys update your vs2019 or delete some files,u should better to check it out that option.
For me it was caused by different web.config files for development and deployment :
development: <aspNetCore requestTimeout="23:00:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" forwardWindowsAuthToken="false" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" startupTimeLimit="3600" hostingModel="InProcess">
deployment : <aspNetCore requestTimeout="23:00:00" processPath=".\Nop.Web.exe" arguments="" forwardWindowsAuthToken="false" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" startupTimeLimit="3600" hostingModel="InProcess">
In my case, I put app_name.exe back from my backup folder to bin\debug, and boom it worked.
If you don't have a backup folder that contains exe so don't worry publish your web app / web API and copy from there
No previous answers worked for me. In my case the "processPath" inside "aspNetCore" tag was pointing to a non-existing folder. A colleague told me that when any value in the web.config is wrong the app doesn't start and emerge this weird error.
In my case, after updating to .Net 6 and using a self contained application I started seeing this error.
I could manually set the module to AspNetCoreModule and the application would run in IIS but I knew this was just a work around since AspNetCoreModuleV2 should be used with .Net 6 applications
I had the following line in the ConfigureServices method:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
Removing the compatibility version resolved my issue.
services.AddMvc();
This is a temporary problem caused by changes in folder or host settings while the application was running.
Most solutions provided here are working because they are indirectly triggering a restart. eg: Changing web.config will trigger a process cleanup and restart for that app.
Solution: Is restart the application process
If the problem still persist after the restart then check EventViewer to see the actual problem, a persistent problem usually means your application has a bug.
I tried changing aspnetCoreModuleV2 to aspnetCoreModuleV2, which worked, but it was a hassle to change every time I published it in Visual Studio.
After testing, I found that I could change the application pool default Settings for IIS to enable 32-bit applications in general.
But I haven't tested it on a 32-bit computer, it should be OK.
See Screenshot.
Fixing all project build errors, would simply fix this issue & the application will load.
Change platform target to Any CPU.

How to deploy jHipster on Azure App Service, I got 500 request timed out

This guideline provided by Microsoft is for SpringBoot App
https://learn.microsoft.com/en-us/azure/app-service/app-service-deploy-spring-boot-web-app-on-azure
which is essentially:
Create an Azure web app for use with Java
Specify the Java version
Obtain FTP deployment credential
Upload your SpringBoot .JAR along with provided web.config
Restart the web app via Azure portal
The app works!
Instead of .jar, jHipster is producing .war file. Since it is essentially the same (i.e. it can be executed with java -jar), I was hoping the steps would also works for .war.
I've uploaded:
the .war file
the .war.original file
web.config
This is the aforementioned web.config. Please note I've renamed the -jar into -war
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform processPath="%JAVA_HOME%\bin\java.exe"
arguments="-Djava.net.preferIPv4Stack=true -Dserver.port=%HTTP_PLATFORM_PORT% -war "%HOME%\site\wwwroot\gmbgenpro-0.0.1-SNAPSHOT.war"">
</httpPlatform>
</system.webServer>
</configuration>
The app is loading so long that I got the 500 request timed out.
EDIT: I've enabled stdout in the web.config and I got the following from the log files:
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Unrecognized option: -war
So it seems I could not use the -war parameter, and I don't know what to do.
To deploy your JHipster project as a WAR file, make sure you build it with spring-boot.repackage.skip option enabled. This will skip building an executable WAR file and simply package the WAR file normally under ${finalName}.war. This way you can deploy your application to a web runtime on Azure automatically configured for you.
To proceed with the deployment, follow these steps:
Add the following Maven Plugin configuration to your main element of your pom.xml:
<plugin>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-webapp-maven-plugin</artifactId>
<!-- check Maven Central for the latest version -->
<version>1.3.0</version>
<configuration>
<resourceGroup>your-resource-group</resourceGroup>
<appName>your-app-name</appName>
<linuxRuntime>tomcat 9.0-jre8</linuxRuntime>-->
</configuration>
</plugin>
Build your project with the following command, and adjust your profile accordingly:
./mvnw clean package -Pdev -Dspring-boot.repackage.skip=true
Deploy your application:
./mvnw azure-webapp:deploy
For up-to-date information about the Maven Plugin for Azure App Service, check the documentation.

Error starting application in .netcore

I'm getting the following error when navigating to my IIS published .netcore application:
I have set up my web.config file as so:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\KritnerWebsite.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />
</system.webServer>
</configuration>
Not sure if this warning is relevant or just outdated:
Severity Code Description Project File Line Source Suppression State
Warning The element 'system.webServer' has invalid child element 'aspNetCore'. List of possible elements expected: 'asp, caching, cgi, defaultDocument, directoryBrowse, globalModules, handlers, httpCompression, webSocket, httpErrors, httpLogging, httpProtocol, httpRedirect, httpTracing, isapiFilters, modules, applicationInitialization, odbcLogging, security, serverRuntime, serverSideInclude, staticContent, tracing, urlCompression, validation, management, rewrite'. KritnerWebsite D:\gitWorkspace\KritnerWebsite\src\KritnerWebsite\web.config 12 Build
The line in the web.config was as per the template, I just changed "false" to "true" for stdoutLogEnabled.
I have also created an empty folder in the root directory "logs" - I wasn't sure if this should get created automatically or not. Either way, nothing is being written to the logs, so I am not sure what to try next.
I have opened the solution in VS2015 on my host, compiled it and ran it successfully through commandline/localhost with dotnet run. This is running it in the production configuration, so pulling from my environment variables for insights key, and connection string. So I'm not sure why the site would run successfully on my host through dotnet run but not when published to IIS
How do I get further information on what the error is?
I'm not sure what exactly caused the logs to start correctly recording in ./logs... but they did. With the exception now being recorded I could see that my connection string I had set up in my Environment Variables was off.
Still not sure what caused the logs to not write out in order for me to determine this faster.
After updating my environment variable and running iisreset as per https://serverfault.com/questions/193609/make-iis-see-updated-environment-path-variable my website is now being served properly.

Publish to IIS, setting Environment Variable

Reading these two questions/answers I was able to run an Asp.net 5 app on IIS 8.5 server.
Asp.net vNext early beta publish to IIS in windows server
How to configure an MVC6 app to work on IIS?
The problem is that the web app is still using env.EnvironmentName with value Development even when run on IIS.
Also, I want to run two versions of the same Web (Staging, Production) on the same server, so I need a method to set the variable for each Web separately.
How to do this?
This answer was originally written for ASP.NET Core RC1. In RC2 ASP.NET Core moved from generic httpPlafrom handler to aspnetCore specific one. Note that step 3 depends on what version of ASP.NET Core you are using.
Turns out environment variables for ASP.NET Core projects can be set without having to set environment variables for user or having to create multiple commands entries.
Go to your application in IIS and choose Configuration Editor.
Select Configuration Editor
Choose system.webServer/aspNetCore (RC2 and RTM) or system.webServer/httpPlatform (RC1) in Section combobox
Choose Applicationhost.config ... in From combobox.
Right click on enviromentVariables element, select 'environmentVariables' element, then Edit Items.
Set your environment variables.
Close the window and click Apply.
Done
This way you do not have to create special users for your pool or create extra commands entries in project.json.
Also, adding special commands for each environment breaks "build once, deploy many times" as you will have to call dnu publish separately for each environment, instead of publish once and deploying resulting artifact many times.
Updated for RC2 and RTM, thanks to Mark G and tredder.
Update web.config with an <environmentVariables> section under <aspNetCore>
<configuration>
<system.webServer>
<aspNetCore .....>
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
Or to avoid losing this setting when overwriting web.config, make similar changes to applicationHost.config specifying the site location as #NickAb suggests.
<location path="staging.site.com">
<system.webServer>
<aspNetCore>
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
<location path="production.site.com">
<system.webServer>
<aspNetCore>
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
You could alternatively pass in the desired ASPNETCORE_ENVIRONMENT into the dotnet publish command as an argument using:
/p:EnvironmentName=Staging
e.g.:
dotnet publish /p:Configuration=Release /p:EnvironmentName=Staging
This will generate out the web.config with the correct environment specified for your project:
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
</environmentVariables>
Edit: as of RC2 and RTM releases, this advice is out of date. The best way I have found to accomplish this in release is to edit the following web.config sections in IIS for each environment:
system.webServer/aspNetCore:
Edit the environmentVariable entry and add an environment variable setting:
ASPNETCORE_ENVIRONMENT : < Your environment name >
As an alternative to drpdrp's approach, you can do the following:
In your project.json, add commands that pass the ASPNET_ENV variable directly to Kestrel:
"commands": {
"Development": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Development",
"Staging": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Staging",
"Production": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Production"
}
When publishing, use the --iis-command option to specify an environment:
dnu publish --configuration Debug --iis-command Staging --out "outputdir" --runtime dnx-clr-win-x86-1.0.0-rc1-update1
I found this approach to be less intrusive than creating extra IIS users.
Just add <EnvironmentName> to your publish profile:
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
That information gets copied to web.config. (Don't set web.config manually since it gets overwritten.)
Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments
I have my web applications (PRODUCTION, STAGING, TEST) hosted on IIS web server. So it was not possible to rely on ASPNETCORE_ENVIRONMENT operative's system enviroment variable, because setting it to a specific value (for example STAGING) has effect on others applications.
As work-around, I defined a custom file (envsettings.json) within my visualstudio solution:
with following content:
{
// Possible string values reported below. When empty it use ENV variable value or Visual Studio setting.
// - Production
// - Staging
// - Test
// - Development
"ASPNETCORE_ENVIRONMENT": ""
}
Then, based on my application type (Production, Staging or Test) I set this file accordly: supposing I am deploying TEST application, i will have:
"ASPNETCORE_ENVIRONMENT": "Test"
After that, in Program.cs file just retrieve this value and then set the webHostBuilder's enviroment:
public class Program
{
public static void Main(string[] args)
{
var currentDirectoryPath = Directory.GetCurrentDirectory();
var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();
var webHostBuilder = new WebHostBuilder()
.UseKestrel()
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true")
.UseContentRoot(currentDirectoryPath)
.UseIISIntegration()
.UseStartup<Startup>();
// If none is set it use Operative System hosting enviroment
if (!string.IsNullOrWhiteSpace(enviromentValue))
{
webHostBuilder.UseEnvironment(enviromentValue);
}
var host = webHostBuilder.Build();
host.Run();
}
}
Remember to include the envsettings.json in the publishOptions (project.json):
"publishOptions":
{
"include":
[
"wwwroot",
"Views",
"Areas/**/Views",
"envsettings.json",
"appsettings.json",
"appsettings*.json",
"web.config"
]
},
This solution make me free to have ASP.NET CORE application hosted on same IIS, independently from envoroment variable value.
Other than the options mentioned above, there are a couple of other Solutions which works well with automated deployments or require fewer configuration changes.
1. Modifying the project file (.CsProj) file
MSBuild supports the EnvironmentName Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.
Simply open the project file (*.csProj) and add the following XML.
<!-- Custom Property Group added to add the Environment name during publish
The EnvironmentName property is used during the publish for the Environment variable in web.config
-->
<PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>
Above code would add the environment name as Development for Debug configuration or if no configuration is specified. For any other Configuration the Environment name would be Production in the generated web.config file. More details here
2. Adding the EnvironmentName Property in the publish profiles.
We can add the <EnvironmentName> property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml} This will set the Environment name in web.config when the project is published. More Details here
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
3. Command line options using dotnet publish
Additionaly, we can pass the property EnvironmentName as a command line option to the dotnet publish command. Following command would include the environment variable as Development in the web.config file.
dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development
After extensive googling I found a working solution, which consists of two steps.
The first step is to set system wide environment variable ASPNET_ENV to Production and Restart the Windows Server. After this, all web apps are getting the value 'Production' as EnvironmentName.
The second step (to enable value 'Staging' for staging web) was rather more difficult to get to work correctly, but here it is:
Create new windows user, for example StagingPool on the server.
For this user, create new user variable ASPNETCORE_ENVIRONMENT with value 'Staging' (you can do it by logging in as this user or through regedit)
Back as admin in IIS manager, find the Application Pool under which the Staging web is running and in Advanced Settings set Identity to user StagingPool.
Also set Load User Profile to true, so the environment variables are loaded. <- very important!
Ensure the StagingPool has access rights to the web folder and Stop and Start the Application Pool.
Now the Staging web should have the EnvironmentName set to 'Staging'.
Update: In Windows 7+ there is a command that can set environment variables from CMD prompt also for a specified user. This outputs help plus samples:
>setx /?
To extend on #tredder's answer you can alter the environmentVariables using appcmd
Staging
%windir%\system32\inetsrv\appcmd set config "staging.example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging'] /commit:APPHOST
Production
%windir%\system32\inetsrv\appcmd set config "example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Production'] /commit:APPHOST
Similar to other answers, I wanted to ensure my ASP.NET Core 2.1 environment setting persisted across deployments, but also only applied to the specific site.
According to Microsoft's documentation, it is possible to set the environment variable on the app pool using the following PowerShell command in IIS 10:
$appPoolName = "AppPool"
$envName = "Development"
cd "$env:SystemRoot\system32\inetsrv"
.\appcmd.exe set config -section:system.applicationHost/applicationPools /+"[name='$appPoolName'].environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='$envName']" /commit:apphost
I unfortunately still have to use IIS 8.5 and thought I was out of luck. However, it is still possible to run a simple PowerShell script to set a site-specific environment variable value for ASPNETCORE_ENVIRONMENT:
Import-Module -Name WebAdministration
$siteName = "Site"
$envName = "Development"
Set-WebConfigurationProperty -PSPath IIS:\ -Location $siteName -Filter /system.webServer/aspNetCore/environmentVariables -Name . -Value #{ Name = 'ASPNETCORE_ENVIRONMENT'; Value = $envName }
What you need to know in one place:
For environment variables to override any config settings, they must be prefixed with ASPNETCORE_.
If you want to match child nodes in your JSON config, use : as a separater. If the platform doesn't allow colons in environment variable keys, use __ instead.
You want your settings to end up in ApplicationHost.config. Using the IIS Configuration Editor will cause your inputs to be written to the application's Web.config -- and will be overwritten with the next deployment!
For modifying ApplicationHost.config, you want to use appcmd.exe to make sure your modifications are consistent. Example: %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /+"environmentVariables.[name='ASPNETCORE_AWS:Region',value='eu-central-1']" /commit:site
Characters that are not URL-safe can be escaped as Unicode, like %u007b for left curly bracket.
To list your current settings (combined with values from Web.config): %systemroot%\system32\inetsrv\appcmd.exe list config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore
If you run the command to set a configuration key multiple times for the same key, it will be added multiple times! To remove an existing value, use something like %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /-"environmentVariables.[name='ASPNETCORE_MyKey',value='value-to-be-removed']" /commit:site.
#tredder solution with editing applicationHost.config is the one that works if you have several different applications located within virtual directories on IIS.
My case is:
I do have API project and APP project, under the same domain, placed in different virtual directories
Root page XXX doesn't seem to propagate ASPNETCORE_ENVIRONMENT variable to its children in virtual directories and...
...I'm unable to set the variables inside the virtual directory as #NickAb described (got error The request is not supported. (Exception from HRESULT: 0x80070032) during saving changes in Configuration Editor):
Going into applicationHost.config and manually creating nodes like this:
<location path="XXX/app">
<system.webServer>
<aspNetCore>
<environmentVariables>
<clear />
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
<location path="XXX/api">
<system.webServer>
<aspNetCore>
<environmentVariables>
<clear />
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
and restarting the IIS did the job.
I know a lot of answers has been given but in my case I added web.{Environment}.config versions in my project and when publishing for a particular environment the value gets replaced.
For example, for Staging (web.Staging.config)
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location>
<system.webServer>
<aspNetCore>
<environmentVariables xdt:Transform="InsertIfMissing">
<environmentVariable name="ASPNETCORE_ENVIRONMENT"
value="Staging"
xdt:Locator="Match(name)"
xdt:Transform="InsertIfMissing" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
For Release or Production I will do this (web.Release.config)
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location>
<system.webServer>
<aspNetCore>
<environmentVariables xdt:Transform="InsertIfMissing">
<environmentVariable name="ASPNETCORE_ENVIRONMENT"
value="Release"
xdt:Locator="Match(name)"
xdt:Transform="InsertIfMissing" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
Then when publishing I will choose or set the environment name. And this will replace the value of the environment in the eventual web.config file.
For those of you looking to this in an azure devops pipeline, this can be achieved by adding the PowerShell on target machines task and running the following script:
$envVariables = (
#{name='VARIABLE1';value='Value1'},
#{name='VARIABLE2';value='Value2'}
)
Set-WebConfigurationProperty -PSPath IIS:\ -Location $('mySite') -Filter /system.webServer/aspNetCore/environmentVariables -Name . -Value $envVariables
To get the details about the error I had to add ASPNETCORE_ENVIRONMENT environment variable for the corresponding Application Pool system.applicationHost/applicationPools.
Note: the web application in my case was ASP.NET Core 2 web application hosted on IIS 10. It can be done via Configuration Editor in IIS Manager (see Editing Collections with Configuration Editor to figure out where to find this editor in IIS Manager).
I have created a repository for publishing IIS with the environment configuration in Web.config.
https://github.com/expressiveco/AspnetCoreWebConfigForEnvironment
Setup
Get the sections from .csproj and .user.csproj files into your project files.
Get the MyAspNetEnvironment.props, web.development.config and web.production.config files.
Configuration
Change the value of ASPNETCORE_ENVIRONMENT property in user.csproj relevantly.
I have modified the answer which #Christian Del Bianco is given. I changed the process for .net core 2 and upper as project.json file now absolute.
First, create appsettings.json file in root directory. with the content
{
// Possible string values reported below. When empty it use ENV
variable value or Visual Studio setting.
// - Production
// - Staging
// - Test
// - Development
"ASPNETCORE_ENVIRONMENT": "Development"
}
Then create another two setting file appsettings.Development.json and appsettings.Production.json with the necessary configuration.
Add necessary code to set up the environment to Program.cs file.
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
***var currentDirectoryPath = Directory.GetCurrentDirectory();
var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();***
try
{
***CreateWebHostBuilder(args, enviromentValue).Build().Run();***
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of setup related exception");
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args, string enviromentValue) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog()
***.UseEnvironment(enviromentValue);***
}
Add the envsettings.json to your .csproj file for copy to published directory.
<ItemGroup>
<None Include="envsettings.json" CopyToPublishDirectory="Always" />
</ItemGroup>
Now just change the ASPNETCORE_ENVIRONMENT as you want in envsettings.json file and published.

Resources