I have an ASP.NET Core application (.NET Core 2.1). I publish using Visual Studio (VS2019 -> RMB on project -> Publish). Server runs on a Windows Server 2019 Standard, there's an IIS installed.
Currently there are three application instances on the server. One staging instance and two production instances. For configuration I use ASPNETCORE_ENVIRONMENT variable which is set in every publish profile using <EnivronmentName> (so I have two profiles with <EnivronmentName>Production</EnivronmentName> and one with <EnivronmentName>Staging</EnivronmentName>).
I need those environment variables to manage email sending: I need it to work for two production instances but not for the staging instance.
Now let me get closer to the problem. I need to modify those emails (just a little bit) depending on the instance: let's say for production instance A I need email subject to be Instance A, for production instance B I need it to be Instance B.
It seemed logical to me that this should be configured via publish profiles because publish profile is what makes one instance different from another. So I tried to find a way to pass publish profile name or additional environment variable to Startup.cs but didn't succeed.
It would be perfect if publishing process stayed untouched but any help/solution is highly appreciated!
Thanks in advance!
After several hours of searching and coding I finally did it. Thanks to #Crowcoder for guiding me in the right direction.
Warning: solution below works for publishing to IIS! I don't know if it works for any other publishing ways.
So publish profiles do change web.config files. And files store some of the site's settings in IIS. Therefore I needed to somehow change web.config during publishing depending on specified profile.
That's where web.config transformations come into play. One of the ways to apply transformations to web.config is based on used publish profile.
Those are my steps:
In web app directory (next to Startup.cs and Program.cs) I added web config file and named it according to existing publish profile. So imagine you have publish profile named ProfileA. Then you need to name your web config file web.ProfileA.config. Naming is important
I entered following sample there
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location>
<system.webServer>
<aspNetCore>
<environmentVariables xdt:Transform="InsertIfMissing">
<environmentVariable name="ENTER_NAME"
value="ENTER_VALUE"
xdt:Locator="Match(name)"
xdt:Transform="InsertIfMissing"/>
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
Then I published the app using VS as I always do.
As I understand, it searches through web.config in your site directory on host trying to find section <environmentVariables> and adds it if it doesn't exist. Then inside that section it tries to find environment variable by its name (ENTER_NAME in my example) and adds it there with specified value (ENTER_VALUE in my example).
After publishing I went to IIS manager, chose published instance and saw that my variable had been added to the list of environment variables in site configuration. It means that now I can access it through IConfiguration.
A little known feature is that you can actually set the Environment via code before your WebHost starts up. In a .NET Core 3+ project, it would look a bit like this :
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseEnvironment("Production");
webBuilder.UseStartup<Startup>();
});
Note that for projects below .NET Core 3, the UseEnvironment call still exists, but the WebHost builder is slightly changed so you might need to play around to work out where it sits.
For example :
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseEnvironment("Development")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
Because you're setting the environment via Code, you can do things as simple as load a file in the root of your project called "environment.txt" that contains your environment and just use that.
A little more info on this feature here : https://dotnetcoretutorials.com/2017/05/03/environments-asp-net-core/
We recently upgraded a .NET Core 2.1 Web App to .NET 3.1. Ever since, our profiles in launchSettings.json are not properly working. Specifically, the environmentVariables are not loading, with one in particular being "ASPNETCORE_ENVIRONMENT". We use this to switch appSettings.{Environment}.json when debugging locally to target different environments.
In my research, it seems that the web.config is the culprit for this issue. For context, we keep a web.config in our project so we can customize some things for our deployments. The profiles in question use IISExpress, therefore the web.config is taken into consideration.
If I remove the web.config, I can switch launch profiles and they take effect. However, when a web.config is present, the launch profile environment variables do not take effect.
Now even more curious, if I remove just this section from the web.config, the environment variables from launch settings start to work again:
This may be related to the Hosting Model changes going from OutOfProcess (.NET 2.1 default) to InProcess (.NET 3.1 default). In fact, if we force the hostingModel for the project to OutofProcess, the launch profiles work as well, but we'd rather keep InProcess if possible.
So what's going on here? Are we missing some migration step? We followed all the steps on MSDN, starting here and working up to 3.1: https://learn.microsoft.com/en-us/aspnet/core/migration/21-to-22?view=aspnetcore-3.1&tabs=visual-studio
Reproduction Steps
Create a new ASP.NET Core Web Application, 3.1
Create a launchSettings.json profile that uses IISExpress, and has "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "SomeTestValue" }
Run that launch profile and check the environment value on IWebHostEnvironment in Configure of Startup.cs.
Note that the env.EnvironmentName should match "SomeTestValue".
Now add the following web.config file to your project:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<remove name="aspNetCore" />
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" stdoutLogEnabled="false" arguments="%LAUNCHER_ARGS%" hostingModel="inprocess" />
</system.webServer>
</configuration>
Run the same profile and check the environment value. It should be your machines default value ("Production" in most cases, which is the default when none is found/specified).
FIX: Update Visual Studio 2019 to v16.6.3 (Released 1 day earlier!)
Holy moley, it was Visual Studio. I was running VS 2019 16.6.2 and I JUST got the notification to update today to 16.6.3, but postponed it. Well, after researching all over stack, github, msdn, etc, I found these posts that lead me to see it was a bug in the 16.6.2 build of VS (possibly earlier versions as well), and the update that JUST came out fixes it.
Related links to the issue
ASP.Net Core MVC needs <environmentVariables> in web.config to work
which led to:
https://github.com/dotnet/websdk/issues/564#issuecomment-644714341
which led to this comment about the VS update: https://github.com/dotnet/websdk/issues/1510#issuecomment-652012087
The docs linked in that comment don't specifically mention this fix. I couldn't find the full release notes.
https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes#16.6.3
But ANYWAYS, updating to VS 2019 16.6.3 worked. I can keep my aspNetCore web.config settings, and launch profile environment variables now load correctly. Huzzah!
Talk about perfect timing for an update...
Also, many browser tabs and RAM bytes lost their lives in search for this answer. Respect.
We're building an ASP.NET MVC 4 app in Visual Studio 2015. The app uses Elmah.MVC for exception handling. We're three developers; for two of us it's working fine on localhost, but one developer is getting this error (captured by Elmah):
The controller for path '/favicon.ico' was not found or does not implement IController.
This post provides a solution, and I've modified the routes to include it and the developer in question has synced his code:
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
Now nothing shows up in Elmah but the user continues to see a generic error:
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
What could be going on? Thanks.
Update 1: Ripped out the Elmah stuff from Web.config and just had the developer load the app. It gets into an infinite loop trying to authenticate the user, similar to this.
We're using OWIN-MixedAuth, and the issue is more than likely on the IIS Express settings. I'll have the developer try it tomorrow and confirm:
Highlight the project in Visual Studio
Open the 'Properties' panel on the right (or press F4)
Set 'Windows Authentication' to 'Enabled'
Set 'Anonymous Authentication' to 'Enabled'
As the name suggests, it's mixed auth, so both types of authentication have to be enabled.
Update 2: The OWIN-Mixed Auth issue has been fixed. Now, it has something to do with these three HTTP modules in Web.config used by Elmah:
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
</httpModules>
When we comment them out, the one developer is able to get onto the site. What do these modules do? Why would they cause a problem?
Finally resolved the issue. We had to make two changes:
We're using OWIN-MixedAuth, and part of the issue was on the IIS Express settings (under "Development Server" section):
Highlight the project in Visual Studio
Open the 'Properties' panel on the right (or press F4)
Set 'Windows Authentication' to 'Enabled'
Set 'Anonymous Authentication' to 'Enabled'
Another part of the issue: a corrupted applicationhost.config file used by IIS Express:
Ensure you're showing hidden files in Windows Explorer.
Go to the root of your project via Windows Explorer.
Open the hidden .vs folder.
Go to config > applicationhost.config, make a backup, and open it in Notepad (Notepad++ is better).
Compare it to a working applicationhost.config file from one of our machines. We found lots of old sites that were listed in the config file which were not being used anymore.
Once cleaned up, launched the app and it worked.
Add this to your global.asax file.
routes.IgnoreRoute("favicon.ico");
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.
In my ASP.NET 5 application, I generate a drop-down list thanks to the HtmlHelper. Anything works fine in localhost except in production, we have a 500 server error.
I was able to find the cast which is performed, on github, and it's performed into the MVC lib, precisely into the DefaultHtmlGenerator class :
This cast is performed when we want to render a drop-down list depending on the SelectList we pass in parameter.
We can see that the comment specify we have to use at least the version 4.5 of the framework. At the end of the stacktrace we see the version of the framework which is used in production :
However, the version 4.5 is installed on our server, and I tried to insert a web.config file into the wwwroot of the projet to force the target framework :
But it doesn't work, and we indicate correctly the framework we want to use into our project.json :
So my question is : can we use compilation targetFramework="4.5" and httpRuntime targetFramework="4.5" to force IIS for using the version 4.5 ?
NOTE
You are trying to run in IIS managed code. You can't do that. IIS doesn't manage the process anymore. Basically, IIS is going to run an EXE and is going to forward requests to it. That's it.
Check the procedure bellow to properly deploy a DNX application to IIS. Or better, read the documentation right here: http://docs.asp.net/en/latest/publishing/iis.html
Requirements
Windows 7 or better
Windows Server 2008 R2 or better
Have IIS installed
Procedure
First, make sure you have the HTTP Platform Handler installed in your IIS (x86 / x64).
Publish your application to the file system and take the content of the \artifacts\bin\MyWebApp\Release\Publish folder and copy it into your IIS Server.
When configuring your application, target the wwwroot folder that you copied over.
Now you'll need to unlock the system.webServer/handlers section which can be found in IIS Manager on the server node under Configuration Editor. Search for the right section and unlock it from the right action pane.
Make sure that the App Pool is set to No Managed Code. DNX is being run as an external process. IIS doesn't need to know about what it's currently running.
Finally, create a web.config with the following content:
<configuration>
<system.webServer>
<handlers>
<add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform processPath="..\approot\web.cmd" arguments="" stdoutLogEnabled="false" stdoutLogFile="..\logs\stdout.log" startupTimeLimit="3600"></httpPlatform>
</system.webServer>
</configuration>
It should be running at that point.
Source