我正在关注this guide构建我的 Controller 。我执行以下操作。
这是我的 Controller :
// GET api/sth/{sthId}/isValid
[HttpGet("{sthId: int}/isValid")]
[ProducesResponseType(StatusCodes.Status200OK)]
[MyAuthorizeFilter]
public ActionResult<bool> Whatever(int sthId)
{
return this.myService.Whatever(sthId);
}
理论上,这应该转换为 Ok() ActionResult
。但是,如果我编写以下单元测试:
[Fact]
public void Whatever()
{
this.myServiceMock.Setup(x => x.Whatever(It.IsAny<int>())).Returns(true);
-> I DEBUG HERE -> var result = this.myController.Whatever(1);
Assert.IsType<OkObjectResult>(result);
Assert.True((bool)result.Value);
}
我看到我的result
是 ActionResult<bool>
确实,谁的Value
是 true
正如预期的那样,但是 result.Result
一片空白。所以:不Ok
任何行动结果。
我错过了什么?我是否必须明确写 return Ok()
为拿到它,为实现它?用这句话
Implicit cast operators support the conversion of both
T
andActionResult
toActionResult<T>
.T
converts toObjectResult
, which meansreturn new ObjectResult(T);
is simplified toreturn T;
.
在文档中我认为没有必要......?
最佳答案
wraps either an[sic]
TValue
instance or anActionResult
.
另请参阅source ,其构造函数分配 Value
或Result
,永远不会两者兼而有之。
如果未显式设置状态代码,MVC 管道将为响应分配成功状态代码。但我找不到该说法的文档。
这意味着在此测试中获得的响应不会有状态代码或 OkActionResult
任何地方。您可以将其转换为 ObjectResult
,但不会有状态代码。
关于asp.net-core - ActionResult<bool> 中的隐式转换运算符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59453421/