asp.net-core - ActionResult<bool> 中的隐式转换运算符不起作用

标签 asp.net-core .net-core asp.net-core-3.0

我正在关注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);
}

我看到我的resultActionResult<bool>确实,谁的Valuetrue正如预期的那样,但是 result.Result一片空白。所以:不Ok任何行动结果。

我错过了什么?我是否必须明确写 return Ok()为拿到它,为实现它?用这句话

Implicit cast operators support the conversion of both T and ActionResult to ActionResult<T>. T converts to ObjectResult, which means return new ObjectResult(T); is simplified to return T;.

在文档中我认为没有必要......?

最佳答案

ActionResult<TValue> class :

wraps either an[sic] TValue instance or an ActionResult.

另请参阅source ,其构造函数分配 ValueResult ,永远不会两者兼而有之。

如果未显式设置状态代码,MVC 管道将为响应分配成功状态代码。但我找不到该说法的文档。

这意味着在此测试中获得的响应不会有状态代码或 OkActionResult任何地方。您可以将其转换为 ObjectResult ,但不会有状态代码。

关于asp.net-core - ActionResult<bool> 中的隐式转换运算符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59453421/

相关文章:

c# - retrofit - 使用 retrofit 参数(字符串)作为 Controller 参数传递

visual-studio - 在 Docker 容器中运行时的 .NET Core 分析

c# - ASP.NET Core 中的密码重置 token 提供程序 - 找不到 IUserTokenProvider

c# - 如果使用命名空间版本路由,如何在 ASP.Net Core API 中设置 RESTful 属性路由

c# - .Net 5 DateTime.ParseExact 问题

asp.net-core-mvc - SignOut 不会重定向到站点主页

azure - 在应用服务环境中安装 ASP.NET CORE 3.0 扩展?

c# - 如何使用接受 Dapper.Contrib 方法的集合?

c# - 应用程序在 Linux 上运行时连接到 MSSQL Server 2017 超时

.net - ASP.NET Core 3.0 端点路由和自定义中间件