c# - 如何从 IActionResult 中提取列表
问题描述
我正在尝试从返回IActionResult
. 目前它正在返回一个带有状态码、值等的对象。我正在尝试仅访问该值。
List<Batch.Context.Models.Batch> newBatch2 = new List<Batch.Context.Models.Batch>();
var actionResultTask = controller.Get();
actionResultTask.Wait();
newBatch2 = actionResultTask.Result as List<Batch.Context.Models.Batch>;
actionResultTask.Result
返回一个列表,其中包括一个列表“值”,它是一个列表,Batch.Context.Models.Batch
我无法访问该值。将其转换为列表后变为空。
这是控制器
[HttpGet]
[ProducesResponseType(404)]
[ProducesResponseType(200, Type = typeof(IEnumerable<Batch.Context.Models.Batch>))]
[Route("Batches")]
public async Task<IActionResult> Get()
{
var myTask = Task.Run(() => utility.GetAllBatches());
List<Context.Models.Batch> result = await myTask;
return Ok(result);
}
如何以列表的形式访问该值。
解决方案
那是因为 的Result
是Task
派生IActionResult
类,OkObjectResult
使测试异步。等待被测方法。然后执行所需的断言。
例如
public async Task MyTest {
//Arrange
//...assume controller and dependencies defined.
//Act
IActionResult actionResult = await controller.Get();
//Assert
var okResult = actionResult as OkObjectResult;
Assert.IsNotNull(okResult);
var newBatch = okResult.Value as List<Batch.Context.Models.Batch>;
Assert.IsNotNull(newBatch);
//...other assertions.
}
推荐阅读
- jquery - 如何在 jQuery 的 .match() 中使用正则表达式
- php - 如何在文档准备好后创建元素的 jquery ui 自动完成?
- r - 在 RStudio 中按条件分组
- android - 没有这样的属性:variantManager
- testing - Spark Structured Streaming 测试后期数据
- python - python中十六进制字符串的不同解释
- redis - Stack Exchange Redis 客户端超时
- apache-spark - 使用 Spark 读取 Azure Synapse 表
- reactjs - reactjs中的循环和渲染
- java - Java如何使用Intellij中另一个模块的方法