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



我创建了一个Nuget包,它在默认值为Application Nameweb.config文件中插入一个名为ApplicationName的键值对。

有没有一种方法可以获得.Net MVC项目的名称,用户将以可读的格式将包安装到键/值的值中?即不正确:ApplicationName正确:Application Name

如果无法获得项目名称,我想使用某种命令行选项是否可行?

经过几天的思考,以下是我提出的解决方案。

  1. 创建一个web.config转换文件,将键/值对添加到AppSettings部分
  2. 创建一个install.ps1文件,该文件获取项目名称,对其进行解析,并在web.config中注入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-ZW_]|d+)(?<![a-z])',' $&').trim()
# Solution based on answer found on Stackoverflow: http://stackoverflow.com/questions/6901954/can-nuget-edit-a-config-file-or-only-add-to-it
$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)
}

希望这能帮助到其他人!

最新更新