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

向索引添加含特殊字符文档报错,.NET SDK如何设置allowUnsafeKeys?

解决Azure Cognitive Search无效文档键问题

一、在.NET SDK中设置allowUnsafeKeys

根据你使用的SDK版本不同,设置方式略有区别:

1. 新版Azure.Search.Documents SDK(推荐)

使用IndexDocumentsOptions类的AllowUnsafeKeys属性,在上传文档时传入配置:

var searchClient = new SearchClient(
    new Uri("你的搜索服务URI"),
    "你的索引名称",
    new AzureKeyCredential("你的API密钥")
);

var options = new IndexDocumentsOptions
{
    AllowUnsafeKeys = true
};

// 假设documents是你要上传的文档集合
await searchClient.IndexDocumentsAsync(IndexDocumentsBatch.Upload(documents), options);

2. 旧版Microsoft.Azure.Search SDK

使用IndexDocumentsParameters类的AllowUnsafeKeys属性:

var indexClient = new SearchIndexClient(
    new Uri("你的搜索服务URI"),
    "你的索引名称",
    new SearchCredentials("你的API密钥")
);

var parameters = new IndexDocumentsParameters
{
    AllowUnsafeKeys = true
};

await indexClient.Documents.IndexAsync(IndexDocumentsBatch.Upload(documents), parameters);

二、Base64编码后保留实际内容的方案

如果不想禁用安全键检查,可通过编码文档键+存储原键字段的方式解决:

  1. 对包含特殊字符的原始键进行URL安全的Base64编码,用编码后的字符串作为文档的id(即文档键)
  2. 在文档中新增一个字段(比如originalKey),存储未编码的原始键内容

示例代码:

string originalKey = "TESTS123*14";

// 生成URL安全的Base64编码键
string encodedKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(originalKey))
    .Replace('+', '-')
    .Replace('/', '_')
    .TrimEnd('=');

// 构造文档,同时保留原键
var document = new
{
    id = encodedKey,
    originalKey = originalKey,
    // 其他业务字段...
};

// 上传文档(无需设置AllowUnsafeKeys)
await searchClient.IndexDocumentsAsync(IndexDocumentsBatch.Upload(new[] { document }));

这样既符合搜索服务的键格式要求,又能在后续查询、检索时获取到原始的键内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:15:27