IndexController.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.Azure.Cosmos;
  3. using System.Text.Json;
  4. namespace HTEXCosmosDB.Controllers
  5. {
  6. [ProducesResponseType(StatusCodes.Status200OK)]
  7. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  8. [Route("index")]
  9. [ApiController]
  10. public class IndexController: ControllerBase
  11. {
  12. private readonly AzureCosmosFactory _azureCosmosFactory;
  13. public IndexController( AzureCosmosFactory azureCosmosFactory )
  14. {
  15. _azureCosmosFactory = azureCosmosFactory;
  16. }
  17. [HttpPost("message")]
  18. public async Task<IActionResult> Message(JsonElement dto)
  19. {
  20. List<Teacher> teachers = new List<Teacher>();// where c.id in( '1595321354222','1607409409')
  21. await foreach (var item in _azureCosmosFactory.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").
  22. GetItemQueryIteratorSql<Teacher>(queryText: "select value c from c", requestOptions: new Microsoft.Azure.Cosmos.QueryRequestOptions() { PartitionKey= new Microsoft.Azure.Cosmos.PartitionKey("Base") }))
  23. {
  24. teachers.Add(item);
  25. }
  26. List<JsonElement> elements = new List<JsonElement>();
  27. await foreach (var item in _azureCosmosFactory.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").
  28. GetItemQueryStreamIteratorSql(queryText: "select value c from c where c.id in( '1595321354222','1607409409222')", requestOptions: new Microsoft.Azure.Cosmos.QueryRequestOptions() { PartitionKey= new Microsoft.Azure.Cosmos.PartitionKey("Base") }))
  29. {
  30. var json = await JsonDocument.ParseAsync(item.Content);
  31. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  32. {
  33. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  34. {
  35. elements.Add(obj);
  36. }
  37. }
  38. }
  39. return Ok(new { response = teachers,elements });
  40. }
  41. }
  42. public class Teacher
  43. {
  44. public string id { get; set;}
  45. public string name { get; set; }
  46. public string code { get; set; }
  47. public string pk { get; set; }
  48. }
  49. }