I'm trying to deploy an ASP.NET Core application to IIS using VSTS with the following tasks
However, after much googling and browsing through MS docs I couldn't find a way to set environment variables for the deployment. The variables I set in the release definition in environment scope aren't getting set as environment variables.
Any idea how to achieve that?
The environment variables you set in VSTS are just used for the deployment itself (ie anything that VSTS is doing such as building your application or running unit tests), but the runtime application will use whichever ones are on the server hosting it.
You will need to set the environment variables on the IIS server that VSTS is deploying to if you want your deployed application to use them as well. Microsoft docs show how to set this depending on your server: Setting the environment
Update in response to comments:
The reccommended way to set environment variables is on the machine itself - ie. log in to the IIS server you are deploying to and add the ASPNETCORE_ENVIRONMENT environment variable there in system properties -> advanced settings -> environment variables
If for some reason you aren't able to do this, you can set them in the Web.config file (according to that documentation). If you are always setting the same value you should be able to just put what you need in the Web.config like so
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
If you really need the XML transforms (which, honestly, I'm not sure you do in this situation - this is for altering the Web.config file at deployment time based on the build configuration. As somebody else mentioned, with asp.net core the reccommended config setup is appsettings[.environment].json files which are automagically loaded based on the matching machine level ASPNETCORE_ENVIRONMENT env variable), you need to actually define the transformations in a transform file using the correct syntax and have it replace the parts you want to change. This is obviously the more difficult option.
See: How to: Transform Web.config When Deploying a Web Application Project for creating the transformation files and Web.config Transformation Syntax for Web Project Deployment Using Visual Studio for the configuration syntax if you choose to go down that path
Something like this (unable to currently test but this should give you an idea - note the transform namespace on the transform file and the xdt: attributes). I believe the transform file that gets loaded matches the build configuration which you may need to configure as part of the VSTS task:
Web.config
<configuration>
<system.webServer>
<aspNetCore ...>
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
Web.Release.config (transform file for build configuration "Release")
<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="Production" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
For ASP.NET Core 1.x projects with a web.config you can use the below.
Since your deployment has a "Dev" environment, commit to your project the following config file:
web.Dev.config
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0" xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.webServer>
<aspNetCore>
<environmentVariables xdt:Transform="InsertIfMissing" />
<environmentVariables>
<environmentVariable xdt:Transform="InsertIfMissing" xdt:Locator="Match(name)" name="ASPNETCORE_ENVIRONMENT" />
<environmentVariable xdt:Transform="Replace" xdt:Locator="Match(name)" name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
The above will create the environmentVariables section in your web.config if it does not already exist.
Replace "Dev" in web.Dev.config with other environment names as necessary.
ASPNETCORE_ENVIRONMENT used as an example above, change for other
variables.
Remove the xmlns="" attribute from the configuration element above if your web.config does not have the same namespace attribute on the configuration element.
In your project.json, add under publishOptions => include:
"web.dev.config"
In VSTS deployment make sure to check "XML transformation" under the IIS Web App Deploy task:
Here is the powershell script I use within Release pipeline (I don't like setting ASPNETCORE_ENVIRONMENT within the build)
arguments:
-p $(System.DefaultWorkingDirectory)\$(Build.DefinitionName)\drop\testbld-Test\web.config -e Development
Inline Script:
param ([string]$p,[string]$e)
$doc = new-object System.Xml.XmlDocument
$location = "$p"
$doc.Load($location)
$subNode = $doc.CreateElement("environmentVariable")
$node = $doc.CreateElement("environmentVariables")
$doc.SelectSingleNode("//aspNetCore").AppendChild($node)
$doc.SelectSingleNode("//environmentVariables").AppendChild($subNode)
foreach($nd in $subNode) {$nd.SetAttribute("name", "ASPNETCORE_ENVIRONMENT");$nd.SetAttribute("value", "$e");}
$doc.Save($location)
I add it as an argument during the "Publish" step of the build:
/p:EnvironmentName=Development
Then it will be added to the web.config of the build output.
Refer to these steps below:
Set config files properties (e.g. web.config, web.QA.config), Copy to Output Directory: Copy if newer)
.NET Core task (Command: restore)
.NET Core task (command: build)
.NET Core task (Command: publish; Check Publish Web Projects option; Arguments: --configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory); Check Zip Published Projects option)
Publish Build Artifacts (Path to publish:$(build.artifactstagingdirectory))
Open release definition, change environment name (e.g. QA, match the config file name)
IIS Web Deploy task: (Package or Folder: $(System.DefaultWorkingDirectory)\**\*.zip; Check XML transformation option (it is based on Environment name to look for transform source file)
Then the web.[environmentname].config file (e.g. web.QA.config) will be transformed to web.config file.
You also can do it through XDT transform task, (the files can’t be in the zip file, so un-check Zip Published Projects option: step4, and archive files through Archive Files task in release)
Another approach to setting environment variables (other than using the XML transform approach) is to add a Powershell task which uses appCmd command to set environment variables in the ApplicationPool scope
C:\Windows\system32\inetsrv\appcmd.exe set config -section:system.applicationHost/applicationPools /+"[name='XyzPool'].environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Dev']" /commit:apphost
Related
I have a really strange issue where I have a project based nuget feed which one pipeline publishes to, which works fine, then another pipeline which needs to restore a project which uses this nuget feed.
The problem is I have followed all the instructions on this such as:
Make sure Build Service has permissions
Make sure NuGetAuthenticate 0 or 1 is called
Ensure there is a nuget.config with the feed included
So for example the nuget.config looks like:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget" value="https://api.nuget.org/v3/index.json" />
<add key="azure-feed" value="http://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json" />
</packageSources>
</configuration>
Then the pipeline section looks like:
steps:
- task: NuGetAuthenticate#0
- task: DotNetCoreCLI#2
displayName: dotnet restore
inputs:
command: restore
nugetConfigPath: 'nuget.config'
feedsToUse: config
This all works fine in the IDE (VS and Rider) and the pipelines that publish and read the nuget package are all in the same azure devops project as the feed.
When the build runs I see the authenticate step run:
Setting up the credential provider to use the identity '<project> Build Service (<org>)' for feeds in your organization/collection starting with:
https://pkgs.dev.azure.com/<org>/
https://<org>.pkgs.visualstudio.com/
Which is all correct and is pointing to the correct feeds, but when the restore runs the error below occurs:
error NU1301: Unable to load the service index for source http://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json.
All the articles online say to try switching to NuGetAuthenticate#0 or enabling higher level settings to allow build service project scopes to not be constrained, as well as confirming all permissions are correct, none of that has solved the problem.
The issue here is that the feed in the nuget.config file is using http not https and for some reason the nuget authenticate task will ONLY authenticate the https url not the unsecure http one which the IDEs work fine with.
So changing:
<add key="azure-feed" value="http://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json" />
to:
<add key="azure-feed" value="https://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json" />
Fixes it all and it works, this was never mentioned as a possible solution online so I thought it prudent to put here for any future generations who have the same issue.
I'm working on C# project using Gitlab CI and would like to hide secrets in app.config file.
I added one variable in Gitlab and in app.config like this:
<add key="User" value="username" />
<add key="Password" value=$Password />
Then, when i try to build application in gitlab CI using msbuild, i receive an error:
$ msbuild "$PROJECTNAME.sln" /consoleloggerparameters:ErrorsOnly /t:Test_project /maxcpucount /nologo /property:Configuration=Release /verbosity:quiet
app.config(5,33): error MSB3249: Application Configuration file "app.config" is invalid. '$' is an unexpected token. The expected token is '"' or '''. Line 7, position 33. [/builds/project/Test_project/Test_project.Service/Test_project.Service.csproj]
Please advice, how to add Gitlab environment variable in app.config xml file.
For .xml files it should work using ${env.MY_VAR_DEFINED_IN_GITLAB}
Where MY_VAR_DEFINED_IN_GITLAB, as specified, is the variable defined in Gitlab Project (or group) -> Settings -> CI/CD -> Variables
Therefore in your case should work:
<add key="User" value=${env.GITLAB_VAR_USERNAME}/>
<add key="Password" value=${env.GITLAB_VAR_PASSWORD}/>
I have a webapi 2.0 which I am publishing using ftp to my windows 2012 server running IIS 8.5.
I ran into an issue which I can resolved using this link here;
Error 405 – Methods not Allowed in ASP.NET Core PUT and DELETE requests
so by adding;
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
I can fix my PUT and DELETE issues, however whenever I publish I am having to physically edit the web.config to reflect the addition of the above code?
Can anyone tell me how to automatically add this when I publish using ftp with web deploy?
My program.cs has the default build in it;
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
One solution I've done is to create a Powershell script that will modify your web.config file however you need and execute it as a Pre-publish Target.
Keep the script in your project directory and update the .csproj file so that it will run just before publishing the project:
Left click project name in Visual Studio -> "Edit .csproj" and insert this somewhere inside the <Project> tags:
<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish" Condition=" '$(IsCrossTargetingBuild)' != 'true' ">
<Exec Command="powershell.exe -NonInteractive -File Prepublish.ps1" />
</Target>
Edit:
My task was simpler, I just needed to remove the LAUNCHER_ARGS added to the <aspNetCore> element, so I just did a simple string replace with an empty string,
Prepublish.ps1:
(Get-Content web.config).Replace(" arguments=`"%LAUNCHER_ARGS%`"", "") | Set-Content web.config
I just changed my laptop. I am moving my old project done in MVC 4 and was done in Visual Studio 2012. My current Visual Studio in my new laptop is 2017 version.
There is a problem when I want to debug my MVC application. This error comes out after I run the debug:
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.
Most likely causes: A default document is not configured for the
requested URL, and directory browsing is not enabled on the server.
I never set my application to be listed in directory browser. My application is an MVC application which will run global.asax and redirect to my home page.
How can I fix this?
enable directory browsing.
keep this into your web config file then rename the add value="pagename.aspx"
<system.webServer>
<defaultDocument>
<files>
<add value="yourpage.aspx" />
</files>
</defaultDocument>
<directoryBrowse enabled="false" />
</system.webServer>
or
<system.webServer>
<directoryBrowse enabled="true" />
</system.webServer>
You can also enable directory browsing from IIS
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt: C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:system.webServer/directoryBrowse /enabled:true
Got the same error, but MVC5 on VS2017. Eventually found I got the error because i had marked Application_Start() in Global.asax as a static. I did that because i made the mistake of following this Code Analysis recommendation:
This is a potential duplicate of
HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents
Different context since you are trying to debug in IIS express and you are not hosting the application in IIS, however the error is the same and the answers is worth checking out. Could set you on the right path.
Would have commented but don't have enough rep yet.
Make sure you have defined your default application inside the hosts file in your new laptop.
This is a cause for many headache.
See it under:
C:/Windows/System32/Drivers/etc/hosts
I have an ASP.NET MVC application using Form Authentication, with the following configuration in the web.config file:
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
I can successfully publish the application on IIS from within the Visual Studio. But when I browse it in the browser, I get a 500 Internal Server Error with the following description:
Check if your IIS components like ASP.NET 4.6, etc are installed. Sometimes this problem occurs in the lake of IIS main components.
You can check this in "Turn Windows features on or off"
Give your virtual directory root folder all rights (read/write)
make sure the app pool is using the right version of the .net. it is by default pointing to .net 2.0.
Here we go:
Did you register .NET with IIS? If not run the following commands:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
You need to do this from an elevated command prompt (cmd) (...run as admin)
Than you have to create this row in your config file:
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
Follow this tutorial: enter link description here
Hope it helps;)
The error message is telling you that this section is locked, generally in the applicationHost.config file. So you need to unlock it before you can modify it in the web.config file. See this for more info. Optionally run this command to unlock the section.
%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/modules
I would avoid reinstalling .Net and changing permissions until you have tried this.