In a .NET MVC 3.0 Application I have the following configuration in 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>
For debugging, I have the following configuration transform defined:
web.Debug.config
<appSettings>
<add key="SMTPPort" value="58" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>
And I run the application in debug mode, but my SMTP port is still taking the value from the web.config
, not web.Debug.config
.
Can anyone suggest what could be wrong in this configuration?
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 - 2017) 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
toweb.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 followingTransformXml
task to the AfterBuild target. Here you can see I will be transforming theweb.base.config
file using theweb.[configuration].config
and it will save it asweb.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
.
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 theMicrosoft.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:
- Create your config transformations for configurations (Debug, Release, etc)
- Rename
Web.config
file toWeb.base.config
- transformations should automaticly rename accordingly (Web.base.Debug.config
, etc) - 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>
- 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.
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!
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>
Use Octopus Deploy (Community edition is free) and let it transform the web.config
for you. Steps:
- Set up Octopus to deploy your web application
- Make sure your
Web.Release.config
has theBuild Action
property set toContent
just like your mainweb.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:
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
Recently I had the same problem with a older web.config filed 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>
来源:https://stackoverflow.com/questions/8841075/web-config-transform-not-working