我创建了一个Nuget包,它在默认值为Application Name
的web.config
文件中插入一个名为ApplicationName
的键值对。
有没有一种方法可以获得.Net MVC项目的名称,用户将以可读的格式将包安装到键/值的值中?即不正确:正确:ApplicationName
Application Name
如果无法获得项目名称,我想使用某种命令行选项是否可行?
经过几天的思考,以下是我提出的解决方案。
- 创建一个
web.config
转换文件,将键/值对添加到AppSettings
部分 - 创建一个
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)
}
希望这能帮助到其他人!