aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Enable web.config transforms for AspNetCore projects in VS

Open oliverjanik opened this issue 9 years ago • 91 comments

Let me prefix this by saying that I'm no fan of web.config but experience of publishing AspNetCore apps to IIS is really poor.

The configuration system of AspNetCore revolves around ASPNETCORE_ENVIRONMENT variable based on which different configs can be loaded and applied.

Setting this variable for specific deployments is a nightmare and there seems to be a lot of confusion how to go about this:

  • https://github.com/aspnet/Home/issues/1701
  • http://stackoverflow.com/questions/41546943/how-to-set-aspnetcore-environment-to-be-considered--for-publishing-an-asp-net-cor
  • http://stackoverflow.com/questions/43054050/set-aspnetcore-environment-within-build-configuration
  • http://stackoverflow.com/questions/39238850/how-to-set-aspnetcore-environment-in-publish-file
  • http://stackoverflow.com/questions/38761617/net-core-set-environment-variable-in-azure-deployment-task
  • http://stackoverflow.com/questions/40535782/how-to-pass-aspnetcore-environment-variable-to-a-gulp-task-in-vso-build-template

The crux of the problem seems to boil down to 2 problems:

  1. web.config transforms as we know them are not supported in ASP.NET Core projects in VS
  2. the only reasonable way to change ASPNETCORE_ENVIRONMENT is using web.config

Setting a global ASPNETCORE_ENVIRONMENT is not an option as that sets it for every site on a single server. web.config used to be self contained configuration. This dependency on a global env variable is no good in IIS use case.

All in all, I believe the IIS publish story should be of concern as many dev such as myself who are transitioning to AspNetCore want to use their existing infrastructure for deployments and take it step by step. Currently this story is overly complicated and not complete.

Another example where I need web.config transforms: https://github.com/aspnet/Home/issues/1701#issuecomment-298273962

oliverjanik avatar May 01 '17 02:05 oliverjanik

FWIW, I agree. We just need to be clear that it's for IIS settings. The other thing is the fact that we've moved away from having a default web.config in the template so that would need to be figured out.

/cc @sayedihashimi

davidfowl avatar May 01 '17 03:05 davidfowl

Is this just for IIS though? I think the crux of the issue is the use of ASPNETCORE_ENVIRONMENT variable fullstop to let a website know which environment it is in.

I think a pretty common scenario is for various staging/QA environments to be hosted on the same box in the same IIS instance. There might be 3 teams all with their own "environments" that they can deploy to to test their code (Say deploy a particular branch), but they are all using the same box.

If we take some example code for how appsettings.json is switched per environment :

public Startup(IHostingEnvironment env)
{
	var builder = new ConfigurationBuilder()
		.SetBasePath(env.ContentRootPath)
		.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
		.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
		.AddEnvironmentVariables();
	Configuration = builder.Build();
}

The scenario above is not going to work because the environment variable is system wide. It could be IIS, nginix etc sitting infront of it and the swapping of configuration is not going to work.

Most times I have seen the above come up, suggestions have come up to use Docker, or use something like Puppet/Chef to manage app configuration so there is no appsettings.{env}.json, but I think that makes the path from full framework MVC that much harder.

mindingdata avatar May 01 '17 20:05 mindingdata

@mindingdata You can actually control the logic that determines where the environment comes from in your Program.cs. The environment variable is just one way to declare that (the main way). If you want to do something else based on some magic file or time of day then call UseEnvironment(environmentName) on the WebHostBuidler

davidfowl avatar May 01 '17 23:05 davidfowl

Just to clarify, this is absolutely just for IIS config. Current JSON config system for app settings is quite good and I fully recommend it.

oliverjanik avatar May 02 '17 00:05 oliverjanik

To muddy things further: I find that when I use web.config to try to override the system environment setting, it simply doesn't work. When my system environment setting is set to "Development" and I try to set it to "Production" using the web.config (as below), the application still thinks it is running in Development. (ASP.NET Core app running in IIS).

<environmentVariables>
      <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
</environmentVariables>

dkent600 avatar Jun 26 '17 15:06 dkent600

I think this is the right place. I build a N-tier demo and I can't seem to figure out how to inject IHostingEnvironment in to my data access layer project. That project is where I access my database and the only way I got the connection string to that layer was to override the OnConfiguring method with a magic string of the config file.

I also looked at slow-cheetah, but that seems like going around the current method of either "Debug, Release" or "Development, Production" depending on if you are using the VS method or the environment variables.

There must be information that I'm missing. MS can't want everyone to build single tier apps.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
           var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json");
            
            var config = builder.Build();
            var connstr = config.GetConnectionString("connStr");            
            optionsBuilder.UseSqlServer(connstr);
        }

martinRocks avatar Aug 29 '17 15:08 martinRocks

so has there been any progress on this?

we should be able to set the env in the config for an app without resorting to magic

TheBeardedLlama avatar Oct 24 '17 09:10 TheBeardedLlama

Yeah I'd like some progress on this too. Currently have no idea how I'm supposed to publish seperate projects to the same box using different environment variables.

DaleMckeown avatar Oct 25 '17 20:10 DaleMckeown

I ended coming up with a fairly simple solution. In the main appsettings.json file, I specify my desired environment:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ActiveEnvironment": "Development"
}

In Program.CS, I then build an IConfiguration, and set the environment name to the value of the 'ActiveEnvironment', before loading the environment specific configuration file.

public static void Main(string[] args)
{
    WebHost.CreateDefaultBuilder()
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        // Get the environment from our hostContext.
        var env = hostingContext.HostingEnvironment;
        config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        // Build an initial configuration.
        IConfiguration Configuration = config.Build();

        // Set the environment name.
        env.EnvironmentName = Configuration.GetSection("ActiveEnvironment").Value;

        // Load the configuration file for our specific environment.
        config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();
    })
    .UseStartup<Startup>()
    .Build()
    .Run();
}

Obviously, when publishing to different environments, the 'ActiveEnvironment' needs to be changed accordingly.

DaleMckeown avatar Oct 26 '17 08:10 DaleMckeown

@DaleMckeown I was going to do something similar but I had a question about your implementation. I see you are using the Microsoft.AspNetCore.WebHost to create the default configuration. Does this approach still apply for a console application with no web components?

Swazimodo avatar Oct 26 '17 16:10 Swazimodo

@Swazimodo I haven't tried this solution int the context of a console application, so I'm not sure. Best bet its to see if there is an alternative way to setting the environment variables for console applications.

DaleMckeown avatar Oct 26 '17 16:10 DaleMckeown

We took care of this in a different way. We setup our build agent to take the environment specific settings file and overwrite the root settings file with it. Our build makes a separate zip file for each environment that we deploy to.

On Thu, Oct 26, 2017 at 12:48 PM, Dale Mckeown [email protected] wrote:

@Swazimodo https://github.com/swazimodo I haven't tried this solution int the context of a console application, so I'm not sure. Best bet its to see if there is an alternative way to setting the environment variables for console applications.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/aspnet/Home/issues/2019#issuecomment-339728441, or mute the thread https://github.com/notifications/unsubscribe-auth/AAx4bT20JSb0XSzNBIAiiubq9mTVKbW5ks5swLf6gaJpZM4NMx25 .

gsmits avatar Oct 26 '17 17:10 gsmits

It seems all solutions require some kind of post build/publish tweaking? I ended up dropping an empty text file in the app root and pass that in as environment. Did I miss anything?

ThisNoName avatar Nov 04 '17 13:11 ThisNoName

Totally agree with the first post. It's by design pretty flexible but at the end it's turned out to be very hard to automate. For example I have an app which I publish to IIS on another server. Also it runs on local IIS (via folder publish). So I set Development environment in web.config. But then I need to change it onto Production or whatever during publishing. Pretty common task I guess. I believe it's impossible, right? I have to manually edit web.config on remote servers.

Ideally setting Environment should be supported via "dotnet publish" (for any publish target):

dotnet publish ... -environment=Production

dotnet publish could search for web.%Enviroment%.config (Web.Production.config, Web.Development.config) files and merge (transform) it with web.config. At the end we'd have correct value of ASPNETCORE_ENVIRONMENT:

	<environmentVariables>
		<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="value passed to publish" />
	</environmentVariables>			

evil-shrike avatar Nov 16 '17 12:11 evil-shrike

@evil-shrike have a look at https://github.com/nil4/dotnet-transform-xdt for build/publish time config transforms.

nil4 avatar Nov 16 '17 17:11 nil4

A use case, perhaps. I need logs to be written to .\App_Data because my application runner has read/write access to everything under .\App_Data, but can only read everything else under .\ . I use web deploy, and would like to be able to deploy a web.config like this one with the logs folder under App_Data:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath=".\<assembly>.exe" stdoutLogEnabled="true" stdoutLogFile=".\App_Data\logs\stdout" />
  </system.webServer>
</configuration>

You might ask, why not just put those settings in a web.config file instead of web.release.config? Well processPath=".\<executable>.exe" is not where the executable lives when I'm developing locally against IIS Express. So I get the good ol' "HTTP Error 502.5 - Process Failure" error.

jeremycook avatar Jan 26 '18 18:01 jeremycook

We automate our builds using Jenkins and our existing way of doing vars configuration per environment in NetFramework projects is through web.config transforms. So we thought we will be able to do it in dotnet as well.

It turns out that msbuild is still compatible with aspnet core csproj for doing web.config transforms!

We can add the TransformXml publishing task in the Asp.Net Core csproj:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v15.0\Web\Microsoft.Web.Publishing.Tasks.dll" />

Add the specific transform targets:

<Target Name="ConfigDev">
    <TransformXml Source="web.config" Transform="web.dev.config" Destination="web.config" /></Target>

Do some transformations, for example on the ASPNETCORE_ENVIRONMENT variable in the web.dev.config:

<system.webServer>
    <aspNetCore processPath="dotnet" arguments=".\Test.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" >
      <environmentVariables>
        <environmentVariable xdt:Locator="Match(name)" name="ASPNETCORE_ENVIRONMENT" value="dev" xdt:Transform="SetAttributes" />
      </environmentVariables>
    </aspNetCore>
</system.webServer>

Transform web.config using msbuild before running publish:

msbuild Test.csproj /t:ConfigDev

jefraim avatar Jan 27 '18 15:01 jefraim

"Let me prefix this by saying that I'm no fan of web.config but experience of publishing AspNetCore apps to IIS is really poor."

I couldn't agree more with this thread.

After the simplicity of config transformations in regular ASP.Net, this whole dependency on a machine-wide ASPNETCORE_ENVIRONMENT variable stinks.

Even Microsoft's own examples say we can use, say, an appsettings.Production.json file, just by adding this line...

            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

...but it pays no attention to the NAME of the configuration we've chosen. So even when I have chosen my Production configuration, it'll still try to open appsettings.development.json. And no, I don't want to have to manually edit the ASPNETCORE_ENVIRONMENT variable myself each time I publish to a different environment. That's just asking for trouble.

I've yet to see a simple, working example of using appsettings.XXXX.json files. I can't wait for this stuff to finally be finished. (Sigh...)

MikeInSwitzerland avatar Mar 09 '18 07:03 MikeInSwitzerland

Yes, please fix this!!

I have just deployed my first production dotnet core site, and now face the issue that I can't easily have a staging instance on the same server because I don't know how to publish my app onto the same box without it picking up the production settings.

I think I'm going to try @DaleMckeown solution for now, I think it will work but it does feel like a workaround rather than a solution. Environment variables are great but ONLY if you have a 1-1 ratio of servers to environments, and outside of enterprise I doubt that happens often.

willapp avatar Mar 10 '18 11:03 willapp

@willapp My suggestion is definitely a workaround. But it does work - I've had multiple versions of the same app running on the same server for a while now and haven't had any issues.

Just remember to change the 'ActiveEnvironment' setting before you publish and you should be fine.

DaleMckeown avatar Mar 10 '18 12:03 DaleMckeown