您可以按照here 的描述使用 web.config 自定义转换
自定义转换在构建配置、配置文件和环境转换之后最后运行。
为需要 web.config 转换的每个自定义配置添加一个 {CUSTOM_NAME}.transform 文件。
在以下示例中,在 custom.transform 中设置了自定义转换环境变量:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location>
<system.webServer>
<aspNetCore>
<environmentVariables xdt:Transform="InsertIfMissing">
<environmentVariable name="Custom_Specific"
value="Custom_Specific_Value"
xdt:Locator="Match(name)"
xdt:Transform="InsertIfMissing" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
在将 CustomTransformFileName 属性传递给 dotnet publish 命令时应用转换:
dotnet publish --configuration Release /p:CustomTransformFileName=custom.transform
配置文件名称的 MSBuild 属性是 $(CustomTransformFileName)。
之前已经发布过类似的问题:
Can I override a connection string in the web.config for local development?
我认为建议的最佳解决方案如下:
Web.config
<configuration>
<connectionStrings configSource="connectionstrings.config">
</connectionStrings>
</configuration>
connectionstrings.config(不在源代码管理中)
<connectionStrings>
<add name="cs" connectionString="server=.;database=whatever;"/>
</connectionStrings>
每个开发者都可以选择自己本地机器指向哪个数据库,只要connectionstrings.config文件不在源代码管理中(加入忽略列表),就不会有人踩对方的脚。