BadRequest (400) with Substatus 1001 when adding new item in Azure Cosmos DB using Microsoft.Azure.CosmosRepository library

huangapple go评论115阅读模式
英文:

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, Nullable1 partitionKey, ItemRequestOptions
requestOptions, CancellationToken cancellationToken)
在Microsoft.Azure.Cosmos.ClientContextCore.RunWithDiagnosticsHelperAsync[TResult](String
containerName, String databaseName, OperationType operationType,
ITrace trace, Func2 task, Func2 openTelemetry, String operationName,
RequestOptions requestOptions)
在Microsoft.Azure.Cosmos.ClientContextCore.OperationHelperWithRootTraceAsync[TResult](String
operationName, String containerName, String databaseName,
OperationType operationType, RequestOptions requestOptions, Func2 task, Func2 openTelemetry, TraceComponent traceComponent, TraceLevel
traceLevel)
在Microsoft.Azure.CosmosRepository.DefaultRepository`1.CreateAsync(TItem
value, CancellationToken cancellationToken)

以下是AddEmailTemplate方法的代码:

  1. private async Task AddEmailTemplate(AddEmailTemplateCommand command)
  2. {
  3. var emailTemplateExist = await _repository
  4. .GetAsync(x => x.NotificationType == command.NotificationType
  5. && x.NotificationSubType == command.NotificationSubType
  6. && x.Language == command.Language).FirstOrDefaultAsync();
  7. // 插入电子邮件模板
  8. if (emailTemplateExist == null)
  9. {
  10. var emailTemplate = new EmailTemplate
  11. {
  12. Id = Guid.NewGuid().ToString(),
  13. NotificationType = command.NotificationType,
  14. NotificationSubType = command.NotificationSubType,
  15. EmailSubject = command.EmailSubject,
  16. Language = command.Language,
  17. TemplateId = command.TemplateId,
  18. };
  19. await _repository.CreateAsync(emailTemplate);
  20. }
  21. else
  22. {
  23. string message = $"已存在指定通知类型的电子邮件模板:{command.NotificationType}";
  24. _logger.LogWarning(message);
  25. throw new EmailTemplateAlreadyExistsException(message);
  26. }
  27. }

EmailTemplate类如下:

  1. [Container(nameof(EmailTemplate))]
  2. [PartitionKeyPath("/NotificationType")]
  3. public class EmailTemplate : Item
  4. {
  5. [JsonProperty(PropertyName = "NotificationType")]
  6. public int NotificationType { get; set; }
  7. [JsonProperty(PropertyName = "NotificationSubType")]
  8. public string NotificationSubType { get; set; }
  9. [JsonProperty(PropertyName = "Language")]
  10. public string Language { get; set; }
  11. [JsonProperty(PropertyName = "TemplateId")]
  12. public string TemplateId { get; set; }
  13. [JsonProperty(PropertyName = "EmailSubject")]
  14. public string EmailSubject { get; set; }
  15. protected override string GetPartitionKeyValue() => NotificationType.ToString();
  16. [JsonProperty(PropertyName = "_ts")]
  17. public long Timestamp { get; set; }
  18. [JsonIgnore]
  19. public DateTime TimestampAsDateTime => DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
  20. }

appsettings.json配置如下:

  1. "RepositoryOptions": {
  2. "CosmosConnectionString": "AccountEndpoint={CosmosDbConnectionString}",
  3. "DatabaseId": "TestDb",
  4. "OptimizeBandwidth": true,
  5. "ContainerPerItemType": true,
  6. "AllowBulkExecution": true,
  7. "SerializationOptions": {
  8. "IgnoreNullValues": true,
  9. "PropertyNamingPolicy": "Default"
  10. }
  11. }

Cosmos DB容器的截图:

BadRequest (400) with Substatus 1001 when adding new item in Azure Cosmos DB using Microsoft.Azure.CosmosRepository library

我会感激任何关于如何解决此问题的见解或建议。在这种情况下,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)
> at Microsoft.Azure.Cosmos.ContainerCore.CreateItemAsync[T](T item, ITrace trace, Nullable
1 partitionKey, ItemRequestOptions
> requestOptions, CancellationToken cancellationToken)
> at Microsoft.Azure.Cosmos.ClientContextCore.RunWithDiagnosticsHelperAsync[TResult](String
> containerName, String databaseName, OperationType operationType,
> ITrace trace, Func2 task, Func2 openTelemetry, String operationName,
> RequestOptions requestOptions)
> at 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)
> at Microsoft.Azure.CosmosRepository.DefaultRepository`1.CreateAsync(TItem
> value, CancellationToken cancellationToken)

  1. private async Task AddEmailTemplate(AddEmailTemplateCommand command)
  2. {
  3. var emailTemplateExist = await _repository
  4. .GetAsync(x => x.NotificationType == command.NotificationType
  5. && x.NotificationSubType == command.NotificationSubType
  6. && x.Language == command.Language).FirstOrDefaultAsync();
  7. // Insert email template
  8. if (emailTemplateExist == null)
  9. {
  10. var emailTemplate = new EmailTemplate
  11. {
  12. Id = Guid.NewGuid().ToString(),
  13. NotificationType = command.NotificationType,
  14. NotificationSubType = command.NotificationSubType,
  15. EmailSubject = command.EmailSubject,
  16. Language = command.Language,
  17. TemplateId = command.TemplateId,
  18. };
  19. await _repository.CreateAsync(emailTemplate);
  20. }
  21. else
  22. {
  23. string message = $"Email template already exists for the specified notification type:{command.NotificationType}";
  24. _logger.LogWarning(message);
  25. throw new EmailTemplateAlreadyExistsException(message);
  26. }
  27. }

EmailTemplate class:

  1. [Container(nameof(EmailTemplate))]
  2. [PartitionKeyPath("/NotificationType")]
  3. public class EmailTemplate : Item
  4. {
  5. [JsonProperty(PropertyName = "NotificationType")]
  6. public int NotificationType { get; set; }
  7. [JsonProperty(PropertyName = "NotificationSubType")]
  8. public string NotificationSubType { get; set; }
  9. [JsonProperty(PropertyName = "Language")]
  10. public string Language { get; set; }
  11. [JsonProperty(PropertyName = "TemplateId")]
  12. public string TemplateId { get; set; }
  13. [JsonProperty(PropertyName = "EmailSubject")]
  14. public string EmailSubject { get; set; }
  15. protected override string GetPartitionKeyValue() => NotificationType.ToString();
  16. [JsonProperty(PropertyName = "_ts")]
  17. public long Timestamp { get; set; }
  18. [JsonIgnore]
  19. public DateTime TimestampAsDateTime => DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
  20. }

appsettings.json:

  1. "RepositoryOptions": {
  2. "CosmosConnectionString": "AccountEndpoint={CosmosDbConnectionString}",
  3. "DatabaseId": "TestDb",
  4. "OptimizeBandwidth": true,
  5. "ContainerPerItemType": true,
  6. "AllowBulkExecution": true,
  7. "SerializationOptions": {
  8. "IgnoreNullValues": true,
  9. "PropertyNamingPolicy": "Default"
  10. }
  11. }

Cosmos Db Container:

BadRequest (400) with Substatus 1001 when adding new item in Azure Cosmos DB using Microsoft.Azure.CosmosRepository library

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.

huangapple
  • 本文由 发表于 2023年7月11日 02:32:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定