You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中构造含单引号的Azure Cosmos DB动态查询

在C#中构造Azure Cosmos DB含特殊字符的动态查询解决方案

问题原因

你之前的代码里,C#字符串中的\'是转义单引号的语法,最终生成的字符串只会保留单引号;而Cosmos DB的SQL需要用\'来转义字符串内的单引号,所以直接写\'无法生成正确的查询语句。

解决方法

方法1:手动转义特殊字符

对输入字符串中的单引号进行替换,把每个'替换为\\'(C#里两个反斜杠代表一个实际的反斜杠),这样生成的SQL语句就会包含正确的\'转义符:

// 运行时输入的目标字符串
string inputValue = "test.a'lcarte";
// 替换单引号为符合Cosmos要求的转义格式
string escapedValue = inputValue.Replace("'", "\\'");
// 拼接最终查询字符串
string _queryText = $"SELECT distinct value c.createdby FROM c where c.createdby in('{escapedValue}') and c.isactive!=false";

此时生成的SQL语句为:

SELECT distinct value c.createdby FROM c where c.createdby in('test.a\'lcarte') and c.isactive!=false

完全匹配Cosmos DB查询编辑器的正确格式。

方法2:使用参数化查询(推荐)

手动拼接字符串存在SQL注入风险,且处理转义容易出错,更安全可靠的方式是使用Cosmos DB的参数化查询,由SDK自动处理特殊字符:

using Microsoft.Azure.Cosmos;

// 运行时输入的目标值
string targetCreatedBy = "test.a'lcarte";

// 构造参数化查询对象
var querySpec = new SqlQuerySpec(
    queryText: "SELECT distinct value c.createdby FROM c where c.createdby in(@createdByValue) and c.isactive!=false",
    parameters: new SqlParameterCollection
    {
        new SqlParameter("@createdByValue", targetCreatedBy)
    }
);

// 执行查询示例(需结合你的Cosmos容器实例)
// FeedIterator<string> iterator = container.GetItemQueryIterator<string>(querySpec);
// while (iterator.HasMoreResults)
// {
//     FeedResponse<string> response = await iterator.ReadNextAsync();
//     // 处理查询结果
// }

这种方式无需手动处理转义,SDK会自动处理参数中的特殊字符,同时彻底规避SQL注入风险,是生产环境的首选方案。

内容的提问来源于stack exchange,提问作者Nitin Arote

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:42:45