Web 配置转换无效

在.NET MVC 3.0应用程序中,我在 appSettings中有以下配置:

Web.config

<appSettings>
<add key="SMTPHost" value="mail.domain.com"/>
<add key="SMTPUsername" value="user@gmail.com"/>
<add key="SMTPPort" value="25"/>
<add key="SMTPPwd" value="mypassword"/>
<add key="EmailFrom" value="notific@gmail.com"/>
</appSettings>

为了调试,我定义了以下配置转换:

调试

<appSettings>
<add  key="SMTPPort" value="58" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>

并且我在调试模式下运行应用程序,但是我的 SMTP 端口仍然从 web.config而不是 web.Debug.config获取值。

有人能提出这种配置可能出现的问题吗?

81430 次浏览

The Web.config transforms are only applied as part of a publish operation.

If you wish this to be done as part of an app.config build operation, then you can use the SlowCheetah - XML Transforms Visual Studio plugin:

http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5

Visual Studio (2010 - 2019) does unfortunately not directly support it while you are debugging, it is only intended for publishing - even with the extension SlowCheetah (marked answer) it does not work for me (only for projects using app.config rather than web.config).

Note that there is a workaround described at codeproject.

It describes how to modify the .msproj file to overwrite the current web.config by the transformed version.

I will first describe that workaround as Option 1, but I have recently found out another Option 2, which is easier to use (so you may scroll down to option 2 directly if you like):


Option 1: I have added the instructions taken from the original codeproject article (see the link above), because the screen shots there are already gone, and I don't want to lose the entire information:

VS.Net doesn't do any transforming when you are developing and just debugging your local environment. But there are some steps you can do to make this happen if you want.

  • First, create the configurations you want in VS.Net, assuming the default debug and release are not enough for what you are trying to accomplish.
  • Right click on your web.config and select Add Config Transforms - this will create a dependant transformation config for each of your configurations defined.
  • Now you can rename your web.config to web.base.config.
  • Add a web.config to your project. It doesn't matter what is in it because it will get overwritten every time we do a build but we want it part of the project so VS.Net doesn't give us the "Your Project isn't configured for Debugging" pop-up.
  • Edit your .csproj Project File and add the following TransformXml task to the AfterBuild target. Here you can see I will be transforming the web.base.config file using the web.[configuration].config and it will save it as web.config. For details, please check this Microsoft Q&A, and for instructions how to extend the build, look there.

Option 2:

Based on this answer, I have developed a simple console app, TransformConfig.exe (in C# 6.0 syntax):

using System;
using System.Linq;
using Microsoft.Web.XmlTransform;


namespace TransformConfig
{


class Program
{
static int Main(string[] args)
{
var myDocumentsFolder = $@"C:\Users\{Environment.UserName}\Documents";
var myVsProjects = $@"{myDocumentsFolder}\Visual Studio 2015\Projects";


string srcConfigFileName = "Web.config";
string tgtConfigFileName = srcConfigFileName;
string transformFileName = "Web.Debug.config";
string basePath = myVsProjects + @"\";
try
{


var numArgs = args?.Count() ?? 0;
if (numArgs == 0 || args.Any(x=>x=="/?"))
{
Console.WriteLine("\nTransformConfig - Usage:");
Console.WriteLine("\tTransformConfig.exe /d:tgtConfigFileName [/t:transformFileName [/s:srcConfigFileName][/b:basePath]]");
Console.WriteLine($"\nIf 'basePath' is just a directory name, '{basePath}' is preceeded.");
Console.WriteLine("\nTransformConfig - Example (inside PostBuild event):");
Console.WriteLine("\t\"c:\\Tools\\TransformConfig.exe\"  /d:Web.config /t:Web.$(ConfigurationName).config /s:Web.Template.config /b:\"$(ProjectDir)\\\"");
Environment.ExitCode = 1;
return 1;
}


foreach (var a in args)
{
var param = a.Trim().Substring(3).TrimStart();
switch (a.TrimStart().Substring(0,2).ToLowerInvariant())
{
case "/d":
tgtConfigFileName = param ?? tgtConfigFileName;
break;
case "/t":
transformFileName = param ?? transformFileName;
break;
case "/b":
var isPath = (param ?? "").Contains("\\");
basePath = (isPath == false)
? $@"{myVsProjects}\" + param ?? ""
: param;
break;
case "/s":
srcConfigFileName = param ?? srcConfigFileName;
break;
default:
break;
}
}
basePath = System.IO.Path.GetFullPath(basePath);
if (!basePath.EndsWith("\\")) basePath += "\\";
if (tgtConfigFileName != srcConfigFileName)
{
System.IO.File.Copy(basePath + srcConfigFileName,
basePath + tgtConfigFileName, true);
}
TransformConfig(basePath + tgtConfigFileName, basePath + transformFileName);
Console.WriteLine($"TransformConfig - transformed '{basePath + tgtConfigFileName}' successfully using '{transformFileName}'.");
Environment.ExitCode = 0;
return 0;
}
catch (Exception ex)
{
var msg = $"{ex.Message}\nParameters:\n/d:{tgtConfigFileName}\n/t:{transformFileName}\n/s:{srcConfigFileName}\n/b:{basePath}";
Console.WriteLine($"TransformConfig - Exception occurred: {msg}");
Console.WriteLine($"TransformConfig - Processing aborted.");
Environment.ExitCode = 2;
return 2;
}
}


public static void TransformConfig(string configFileName, string transformFileName)
{
var document = new XmlTransformableDocument();
document.PreserveWhitespace = true;
document.Load(configFileName);


var transformation = new XmlTransformation(transformFileName);
if (!transformation.Apply(document))
{
throw new Exception("Transformation Failed");
}
document.Save(configFileName);
}


}
}

Ensure that you add the DLL "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.XmlTransform.dll"as a reference (this example applies to VS 2015, for older versions replace the v14.0 in the path by the appropriate version number, e.g. v11.0).

For Visual Studio 2017, the naming schema for the path has changed: For example, for the enterprise version it is here: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\Web.
I assume that for the professional version you need to replace Enterprise in the path by Professional. If you're using the preview version, additionally replace 2017 by Preview.

Here's an overview how the path has changed for different versions of Visual Studio (if you don't have the Enterprise version you might need to replace Enterprise by Professional in the path):

VS Version        Path (for Microsoft.Web.XmlTransform.dll)
2015                  C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web
2017                  C:\Program Files (x86)\Microsoft Visual Studio\2017\
                          Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\Web
2019                  C:\Program Files (x86)\Microsoft Visual Studio\2019\
                          Enterprise\MSBuild\Microsoft\VisualStudio\v16.0\Web

Compile it and put the .exe file into a directory, e.g. C:\MyTools\.

Usage: You can use it in your post build event (in project properties, select Build Events, then edit the Post-build event command line). Commandline parameters are (example):

"C:\MyTools\TransformConfig.Exe" /d:Web.config /t:Web.$(ConfigurationName).config /s:Web.Template.config /b:"$(ProjectDir)\"

i.e. first the name of the config file, followed by the transform config file, followed by an optional template config, followed by the path to your project containing both files.

I have added the optional template config parameter because otherwise your original complete config would be overwritten by the transform, which can be avoided by providing a template.

Create the template by simply copying the original Web.config and name it Web.Template.config.

Note:

  • If you prefer, you can also copy the TransformConfig.exe file to the Visual Studio path mentioned above where the Microsoft.Web.XmlTransform.dll resides and refer to it in all your projects where you need to transform your configs.

  • For those of you who are wondering why I added Environment.ExitCode = x; assignments: Simply returning an int from Main did not help in the build event. See details here.

  • If you're publishing your project and you're using a Web.Template.config, ensure that you did a rebuild on your solution with the right configuration (usually Release) before you publish. The reason is that the Web.Config is overwritten during debugging and you might end up transforming the wrong file otherwise.

Answering your question isn't simple, because it poses a problem - if you want to transform Web.config with Web.debug.config - where transformation effect should be stored? In Web.config itself? This would overwrite transformation source file! Probably that's why Visual Studio doesn't do transformations during builds.

Previous Matt answer is valid, but you might want to mix them to have generic solution that works when you actually change active solution configuration from debug to release etc. Here's a simple solution:

  1. Create your config transformations for configurations (Debug, Release, etc)
  2. Rename Web.config file to Web.base.config - transformations should automaticly rename accordingly (Web.base.Debug.config, etc)
  3. Add following transformWebConfig.proj XML file to your project folder:
<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="4.0" DefaultTargets="TransformWebConfig" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">


<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="TransformWebConfig">
<TransformXml Source="Web.base.config" Transform="Web.base.$(CurrentConfig).config" Destination="Web.config" />
</Target>
</Project>
  1. Navigate to your project properties, choose Build Events and add following content to Post-build event command line:
@if exist "%ProgramFiles(x86)%\MSBuild\12.0\bin" set PATH=%ProgramFiles(x86)%\MSBuild\12.0\bin;%PATH%
msbuild $(ProjectDir)transformWebConfig.proj /t:TransformWebConfig /p:CurrentConfig=$(ConfigurationName) /p:TargetProjectName=$(TargetPath)

Now, when you build your solution, a Web.config file will be created with valid transformations for active configuration.

Apparently there's a extension for Visual Studio 2015

https://visualstudiogallery.msdn.microsoft.com/05bb50e3-c971-4613-9379-acae2cfe6f9e

This package enables you to transform your app.config or any other XML file based on the build configuration

Use Octopus Deploy (Community edition is free) and let it transform the web.config for you. Steps:

  1. Set up Octopus to deploy your web application
  2. Make sure your Web.Release.config has the Build Action property set to Content just like your main web.config file.

That's it! Octopus will do the rest without any special config. A default IIS Web Site deploy will do this out of the box:enter image description here

Your immediate question has been answered - the explanation is that the transform is applied on publish, not on build.

However, I think that it does not offer a solution on how to achieve what you want to do.

I have been struggling with this exact problem for a few days now, looking for a way to keep web.config clean and set all keys that vary depending on environment in the respective transform files. My conclusion is that the easiest and most stable solution is to use debug values in the original web.config, that way they are always present when you do debug runs in Visual Studio.

Then create transforms for the different environments you want to publish to - test, integration, production - whatever you have. The now built-in functionality to transform web.config files on publish will suffice for this. No need for SlowCheetah or editing build events nor project files. If you have only web projects that is.

Should you wish to, you could also have the web.debug.config file in your solution, just to keep a separate file with all the values pertaining to the development environment. Be sure to comment in it that the values are not applied when running in Visual Studio though, in case someone else try to use it for that purpose!

Recently I had the same problem with a older web.config file based on .NET Framework 2.0. The solution was simply remove the web.config's namespace (xmlns attibute in configuration root node):

BEFORE: <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

AFTER: <configuration>

for VS 2017 I found the answer here not sure why nobody has referenced it above as it appears to be a very popular solution. Very easy too. Make sure you see the comment from IOrlandoni on Mar5 2019 for making it work in VS 2017 and all versions.

Basically its a two stepper. First, you edit the .csproj file, appending the code below. Second, you create a new web.base.config configuration and copy the existing web.config there. After doing that any build will overwrite your web.config with your desired transformation.

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets" />
<Target Name="BeforeBuild">
<TransformXml Source="Web.Base.config"
Transform="Web.$(Configuration).config" Destination="Web.config" />
</Target>

To make the transform be done at build time:

Exclude the web.config (+ web.*.config) from your project. Then rename the files on disk as follows

  • web.config => Web.Template.config
  • web.Release.config => Web.Transform.Release.config
  • web.Debug.config => Web.Transform.Debug.config

Add the web.config to your gitignore and commit the changes so far.

Finally, in a text editor add the following to the project file.

  <Target Name="BeforeBuild">
<TransformXml Source="Web.Template.config" Transform="Web.Transform.$(Configuration).config" Destination="Web.config" />
</Target>
<ItemGroup>
<Content Include="Web.config" />
<None Include="Web.*.config" />
</ItemGroup>

Now whenever you build the project the Web.Template.config will be transformed by Web.Debug.Transform.config into Web.config if you selected the Debug configuration in Visual Studio. Same for Release.

When Web.config is generated for the first time you may need to restart Visual Studio after the build and then build again to have Visual Studio recognize the generated web.config.

This approach was tested with an ASP.NET (not Core) project on Visual Studio 2019.

Add to your appsetting "xdt:Transform="Replace" attribute. Like below:

  <appSettings xdt:Transform="Replace">
<add  key="SMTPPort" value="58" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>

It will replace whole appsettings with debug config.But if you don't want that you can apply that whatever tag you want. It will include all child elements of that tag. By the way you should set attribute to configuration section also.I mark that below:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">