gpt4 book ai didi

c# - 如何在使用 webdeploy 时用当前日期替换 web.config 设置?

转载 作者:太空狗 更新时间:2023-10-29 20:42:14 25 4
gpt4 key购买 nike

我正在使用 web.config 转换将设置替换为所选解决方案配置的设置。但是,我想添加一个存储发布过程的日期时间的设置。这样做的原因是能够为我的客户显示“最后发布于”。

使用配置转换,有没有办法用当前日期替换设置?

最佳答案

我能够在 Visual Studio 2022 中使用 .NET 6 Web 应用程序执行此操作,方法是使用 PowerShell 脚本添加 <environmentVariable>带有发布时间戳到我的 web.config在发布之前,然后在发布之后将其删除。这样我就不会得到我的本地 web.config每次发布时都会更改源代码管理。

我发布到本地文件夹,然后使用 Beyond Compare 部署到共享生产服务器。已部署 web.config包括时间戳将自动重新启动我的生产 IIS 工作进程,解锁我的主 DLL,除非我触摸我的 web.config,否则无法复制.

  1. 创建一个名为 beforePublish.ps1 的 Powershell 脚本使用此代码:

    $webConfig = "web.config"
    $webConfigXml = (gc $webConfig) -as [Xml]

    $publishTime = $webConfigXml.CreateElement("environmentVariable")
    $publishTime.SetAttribute("name", "PublishTime")
    $publishTime.SetAttribute("value", (Get-Date))
    $webConfigXml.configuration.location.'system.webServer'.aspNetCore.environmentVariables.AppendChild($publishTime)

    $webConfigXml.Save($webConfig)
    • 假设您有一个现有的 environmentVariable<aspNetCore> 中像这样标签:
            <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
    </environmentVariables>
  2. 创建名为 afterPublish.ps1 的 PowerShell 脚本使用此代码:

    $webConfig = "web.config"
    $webConfigXml = (gc $webConfig) -as [Xml]

    $nodes = $webConfigXml.SelectNodes("//environmentVariable[@name='PublishTime']")
    foreach($node in $nodes) { $node.ParentNode.RemoveChild($node) }

    $aspNetCore = $webConfigXml.SelectSingleNode("//aspNetCore")
    $aspNetCore.SetAttribute("processPath", $aspNetCore.GetAttribute("processPath").replace("Release", "Debug"))

    $webConfigXml.Save($webConfig)
    • 如您所见,我还恢复了我的 <aspNetCore processPath='bin\Release\net6.0...'>回到 Debug模式,通过发布到 Release模式保持我的本地主机不变。
  3. 将此 XML 添加到 \Properties\PublishProfiles\FolderProfile.pubxml <Project> 里面的文件标签:

    <Target Name="AddTimestampToWebConfig" BeforeTargets="Publish">
    <Exec Command="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -file D:\Documents\wwwroot\PortalApp\Properties\beforePublish.ps1" />
    </Target>
    <Target Name="RemoveTimestampFromWebConfig" AfterTargets="AfterPublish">
    <Exec Command="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -file D:\Documents\wwwroot\PortalApp\Properties\afterPublish.ps1" />
    </Target>

关于c# - 如何在使用 webdeploy 时用当前日期替换 web.config 设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6827978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com