英文:
BadRequest (400) with Substatus 1001 when adding new item in Azure Cosmos DB using Microsoft.Azure.CosmosRepository library
问题
我在使用Azure Cosmos DB的CreateAsync
方法创建新项时遇到了问题,使用的是Microsoft.Azure.CosmosRepository
库的版本为7.0.1
,在.NET 6 Web API应用程序中。我收到了一个带有Substatus 1001的BadRequest (400)
响应。
以下是详细信息:
我有一个名为AddEmailTemplate
的方法,用于更新存储库中的电子邮件模板。但是,当我执行更新操作时,我收到以下错误消息:
用于项目类型EmailTemplate的Cosmos查询执行,计费为2.8
RUs查询:{"query":"SELECT VALUE root FROM root WHERE
((((root["NotificationType"] = 3) AND (root["NotificationSubType"]
= "")) AND (root["Language"] = "en-US")) AND ((NOT IS_DEFINED(root["Type"])) OR (root["Type"] =
"EmailTemplate")))"}失败:
SFH.N3.WebApi.Controllers.EmailTemplates.EmailTemplateController[0]
发生更新电子邮件模板时出错,RequestId:338bcaa9-f8a3-418b-932b-4d88a7ab6a08
Microsoft.Azure.Cosmos.CosmosException:响应状态代码不表示成功:BadRequest (400);Substatus: 1001;
ActivityId: 5242793b-f785-436d-9565-5d7c1e730ef4;Reason: ();
在Microsoft.Azure.Cosmos.ResponseMessage.EnsureSuccessStatusCode()中
在Microsoft.Azure.Cosmos.CosmosResponseFactoryCore.ProcessMessage[T](ResponseMessage
responseMessage, Func2 createResponse) 在Microsoft.Azure.Cosmos.ContainerCore.CreateItemAsync[T](T item, ITrace trace, Nullable
1 partitionKey, ItemRequestOptions
requestOptions, CancellationToken cancellationToken)
在Microsoft.Azure.Cosmos.ClientContextCore.RunWithDiagnosticsHelperAsync[TResult](String
containerName, String databaseName, OperationType operationType,
ITrace trace, Func2 task, Func
2 openTelemetry, String operationName,
RequestOptions requestOptions)
在Microsoft.Azure.Cosmos.ClientContextCore.OperationHelperWithRootTraceAsync[TResult](String
operationName, String containerName, String databaseName,
OperationType operationType, RequestOptions requestOptions, Func2 task, Func
2 openTelemetry, TraceComponent traceComponent, TraceLevel
traceLevel)
在Microsoft.Azure.CosmosRepository.DefaultRepository`1.CreateAsync(TItem
value, CancellationToken cancellationToken)
以下是AddEmailTemplate
方法的代码:
private async Task AddEmailTemplate(AddEmailTemplateCommand command)
{
var emailTemplateExist = await _repository
.GetAsync(x => x.NotificationType == command.NotificationType
&& x.NotificationSubType == command.NotificationSubType
&& x.Language == command.Language).FirstOrDefaultAsync();
// 插入电子邮件模板
if (emailTemplateExist == null)
{
var emailTemplate = new EmailTemplate
{
Id = Guid.NewGuid().ToString(),
NotificationType = command.NotificationType,
NotificationSubType = command.NotificationSubType,
EmailSubject = command.EmailSubject,
Language = command.Language,
TemplateId = command.TemplateId,
};
await _repository.CreateAsync(emailTemplate);
}
else
{
string message = $"已存在指定通知类型的电子邮件模板:{command.NotificationType}";
_logger.LogWarning(message);
throw new EmailTemplateAlreadyExistsException(message);
}
}
EmailTemplate
类如下:
[Container(nameof(EmailTemplate))]
[PartitionKeyPath("/NotificationType")]
public class EmailTemplate : Item
{
[JsonProperty(PropertyName = "NotificationType")]
public int NotificationType { get; set; }
[JsonProperty(PropertyName = "NotificationSubType")]
public string NotificationSubType { get; set; }
[JsonProperty(PropertyName = "Language")]
public string Language { get; set; }
[JsonProperty(PropertyName = "TemplateId")]
public string TemplateId { get; set; }
[JsonProperty(PropertyName = "EmailSubject")]
public string EmailSubject { get; set; }
protected override string GetPartitionKeyValue() => NotificationType.ToString();
[JsonProperty(PropertyName = "_ts")]
public long Timestamp { get; set; }
[JsonIgnore]
public DateTime TimestampAsDateTime => DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
}
appsettings.json
配置如下:
"RepositoryOptions": {
"CosmosConnectionString": "AccountEndpoint={CosmosDbConnectionString}",
"DatabaseId": "TestDb",
"OptimizeBandwidth": true,
"ContainerPerItemType": true,
"AllowBulkExecution": true,
"SerializationOptions": {
"IgnoreNullValues": true,
"PropertyNamingPolicy": "Default"
}
}
Cosmos DB容器的截图:
我会感激任何关于如何解决此问题的见解或建议。在这种情况下,Substatus 1001是否有特定的含义?我如何进一步调查和解决此错误?
但是,当我检索现有项时,GetAsync
方法工作正常(var emailTemplates = await _repository.GetAsync("{query}");
)。
英文:
I getting an issue while creating a new item with CreateAsync
method in Azure Cosmos DB using the Microsoft.Azure.CosmosRepository
(https://www.nuget.org/packages/IEvangelist.Azure.CosmosRepository) library 7.0.1
version with .NET 6 Web Api application. I am receiving a BadRequest (400) response with Substatus 1001
.
Here are the details:
I have a method AddEmailTemplate
that updates an email template in the repository. However, when I execute the update operation, I receive the following error:
> Cosmos query executed for item type EmailTemplate with a charge of 2.8
> RUs Query: {"query":"SELECT VALUE root FROM root WHERE
> ((((root["NotificationType"] = 3) AND (root["NotificationSubType"]
> = "")) AND (root["Language"] = "en-US")) AND ((NOT IS_DEFINED(root["Type"])) OR (root["Type"] =
> "EmailTemplate")))"} fail:
> SFH.N3.WebApi.Controllers.EmailTemplates.EmailTemplateController[0]
> An error occurred while updating email template, RequestId:338bcaa9-f8a3-418b-932b-4d88a7ab6a08
> Microsoft.Azure.Cosmos.CosmosException : Response status code does not indicate success: BadRequest (400); Substatus: 1001;
> ActivityId: 5242793b-f785-436d-9565-5d7c1e730ef4; Reason: ();
> at Microsoft.Azure.Cosmos.ResponseMessage.EnsureSuccessStatusCode()
> at Microsoft.Azure.Cosmos.CosmosResponseFactoryCore.ProcessMessage[T](ResponseMessage
> responseMessage, Func2 createResponse)
1 partitionKey, ItemRequestOptions
> at Microsoft.Azure.Cosmos.ContainerCore.CreateItemAsync[T](T item, ITrace trace, Nullable
> requestOptions, CancellationToken cancellationToken)
> at Microsoft.Azure.Cosmos.ClientContextCore.RunWithDiagnosticsHelperAsync[TResult](String
> containerName, String databaseName, OperationType operationType,
> ITrace trace, Func2 task, Func
2 openTelemetry, String operationName,
> RequestOptions requestOptions)
> at Microsoft.Azure.Cosmos.ClientContextCore.OperationHelperWithRootTraceAsync[TResult](String
> operationName, String containerName, String databaseName,
> OperationType operationType, RequestOptions requestOptions, Func2
2 openTelemetry, TraceComponent traceComponent, TraceLevel
> task, Func
> traceLevel)
> at Microsoft.Azure.CosmosRepository.DefaultRepository`1.CreateAsync(TItem
> value, CancellationToken cancellationToken)
private async Task AddEmailTemplate(AddEmailTemplateCommand command)
{
var emailTemplateExist = await _repository
.GetAsync(x => x.NotificationType == command.NotificationType
&& x.NotificationSubType == command.NotificationSubType
&& x.Language == command.Language).FirstOrDefaultAsync();
// Insert email template
if (emailTemplateExist == null)
{
var emailTemplate = new EmailTemplate
{
Id = Guid.NewGuid().ToString(),
NotificationType = command.NotificationType,
NotificationSubType = command.NotificationSubType,
EmailSubject = command.EmailSubject,
Language = command.Language,
TemplateId = command.TemplateId,
};
await _repository.CreateAsync(emailTemplate);
}
else
{
string message = $"Email template already exists for the specified notification type:{command.NotificationType}";
_logger.LogWarning(message);
throw new EmailTemplateAlreadyExistsException(message);
}
}
EmailTemplate class:
[Container(nameof(EmailTemplate))]
[PartitionKeyPath("/NotificationType")]
public class EmailTemplate : Item
{
[JsonProperty(PropertyName = "NotificationType")]
public int NotificationType { get; set; }
[JsonProperty(PropertyName = "NotificationSubType")]
public string NotificationSubType { get; set; }
[JsonProperty(PropertyName = "Language")]
public string Language { get; set; }
[JsonProperty(PropertyName = "TemplateId")]
public string TemplateId { get; set; }
[JsonProperty(PropertyName = "EmailSubject")]
public string EmailSubject { get; set; }
protected override string GetPartitionKeyValue() => NotificationType.ToString();
[JsonProperty(PropertyName = "_ts")]
public long Timestamp { get; set; }
[JsonIgnore]
public DateTime TimestampAsDateTime => DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
}
appsettings.json:
"RepositoryOptions": {
"CosmosConnectionString": "AccountEndpoint={CosmosDbConnectionString}",
"DatabaseId": "TestDb",
"OptimizeBandwidth": true,
"ContainerPerItemType": true,
"AllowBulkExecution": true,
"SerializationOptions": {
"IgnoreNullValues": true,
"PropertyNamingPolicy": "Default"
}
}
Cosmos Db Container:
I would appreciate any insights or suggestions on how to resolve this issue. Is there any specific meaning for Substatus 1001 in this context? How can I further investigate and resolve this error?
But GetAsync
method is working fine, when I am retrieving the existing items (var emailTemplates = await _repository.GetAsync("{query}");
答案1
得分: 2
根据该错误代码的文档: https://learn.microsoft.com/azure/cosmos-db/nosql/troubleshoot-bad-request#wrong-partition-key-value
这意味着分区键被错误地指定了。容器的分区键定义与作为分区键发送的属性之间存在不匹配。
请再次检查容器的分区键定义,确保它确实是 /NotificationType
,并且 NotificationType
属性具有正确支持的值类型。
英文:
Based on the documentation for that error code: https://learn.microsoft.com/azure/cosmos-db/nosql/troubleshoot-bad-request#wrong-partition-key-value
It means the Partition Key is incorrectly specified. There is a mismatch between the Container's Partition Key Definition and the property being send as Partition Key.
Double check on the Container's Partition Key Definition if it's indeed /NotificationType
and if the NotificationType
property has a correct supported value type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论