通过C#控制台执行Azure CLI命令时遇JSON转义字符串错误
C#执行Azure CLI更新App Config Targeting过滤器报错解决
问题现象
通过C#控制台应用调用Azure CLI命令更新Azure App Configuration的Microsoft.Targeting过滤器时,触发错误:
ERROR: Filter parameter value must be a JSON escaped string.
将调试时得到的完整命令字符串复制到Azure门户的Bash环境执行,可正常完成更新,但在C#程序中执行相同命令就会报错。
问题原因
Windows命令行(cmd.exe)与Bash的参数解析规则存在差异:
- Bash会自动处理单引号包裹的JSON字符串,无需额外转义
- C#通过
Process调用az.cmd时,cmd无法正确识别单引号内的JSON格式,导致Azure CLI接收到的参数不符合要求
解决方案
需要对JSON参数进行双重转义,并调整命令的引号使用方式,确保cmd能正确解析参数:
修改关键代码
在UpdateAppConfigFilter方法中,替换原有的命令构建逻辑:
string audienceJsonString = JsonConvert.SerializeObject(audienceObject); // 对JSON中的双引号进行转义,替换为\" string escapedAudienceJson = audienceJsonString.Replace("\"", "\\\""); // 使用双引号包裹--filter-parameters的完整参数值,同时转义连接字符串的引号 string command4 = $"appconfig feature filter update --connection-string \"{endpoint}\" --feature {featureName} --filter-name Microsoft.Targeting --filter-parameters \"Audience={escapedAudienceJson}\" --yes"; RunAzureCliCommand(command4);
更严谨的参数传递方式(推荐)
对于.NET Core及以上版本,可使用ProcessStartInfo.ArgumentList直接传递参数数组,彻底避免字符串拼接的转义问题:
public static string RunAzureCliCommand(string[] arguments) { var processStartInfo = new ProcessStartInfo { FileName = "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; // 逐个添加参数,无需手动转义 foreach (var arg in arguments) { processStartInfo.ArgumentList.Add(arg); } using (var process = new Process { StartInfo = processStartInfo }) { process.Start(); string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); if (process.ExitCode == 0) { return output; } else { throw new InvalidOperationException($"Command execution failed. Error: {error}"); } } } // 调用时: string audienceJsonString = JsonConvert.SerializeObject(audienceObject); string[] commandArgs = new[] { "appconfig", "feature", "filter", "update", "--connection-string", endpoint, "--feature", featureName, "--filter-name", "Microsoft.Targeting", "--filter-parameters", $"Audience={audienceJsonString}", "--yes" }; RunAzureCliCommand(commandArgs);
原理说明
- 转义JSON中的双引号为
\",确保cmd将其识别为JSON字符串的一部分,而非参数分隔符 - 使用
ArgumentList传递参数时,.NET会自动处理每个参数的转义逻辑,避免手动处理的失误
内容的提问来源于stack exchange,提问作者Diwakar Reddy
相关产品推荐
相关产品推荐

