用于在 web.config 中插入项目名称的 Nuget 包

Nuget package to insert project name in web.config

我创建了一个 Nuget 包,它在 web.config 文件中插入了一个名为 ApplicationName 的 key/value 对,默认值为 Application Name.

有没有办法以人类可读的格式获取用户将要安装包的 .Net MVC 项目的名称到 key/value 的值中?即不正确:ApplicationName 正确:Application Name

如果无法获取项目名称,我想使用某种命令行选项可以吗?

经过几天的琢磨,这是我想出的解决方案。

  1. 创建一个 web.config 转换文件以将 key/value 对添加到 AppSettings 部分。
  2. 创建一个 install.ps1 文件,获取项目名称,解析它并在 web.config.
  3. 中注入 AppplicationName 的新值

这是我的 web.config.install.xdt 文件:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings xdt:Transform="InsertIfMissing">
    <add key="ApplicationName" value="Application Name" xdt:Transform="InsertIfMissing" xdt:Locator="Match(key)" />
  </appSettings>
</configuration>

这是我的 install.ps1 脚本:

# Runs every time a package is installed in a project
param($installPath, $toolsPath, $package, $project)

# $installPath is the path to the folder where the package is installed.
# $toolsPath is the path to the tools directory in the folder where the package is installed.
# $package is a reference to the package object.
# $project is a reference to the project the package was installed to.

$p = Get-Project
$project_readable_name = ($p.Name -creplace  '([A-Z\W_]|\d+)(?<![a-z])',' $&').trim()

# Solution based on answer found on Whosebug: 
$xml = New-Object xml

# Find the web.config 
$config = $project.ProjectItems | where {$_.Name -eq "Web.config"}

if($config) {
    # Find web.config's path on the file system
    $localPath = $config.Properties | where {$_.Name -eq "LocalPath"}

    # Load Web.config as XML
    $xml.Load($localPath.Value)

    # Select the ApplicationName node
    $node = $xml.SelectSingleNode("configuration/appSettings/add[@key='ApplicationName']")

    # Change the ApplicationName value
    $node.SetAttribute("value", $project_readable_name)

    # Save the Web.config file
    $xml.Save($localPath.Value)
}

希望这对其他人有帮助!