Mit*_*sev 0 .net c# asp.net-mvc .net-core asp.net-core
我开始,返回一个自定义类:
[HttpGet()]
public ActionResult<Round> Get(string id) =>
this._roundsService.Get(id);
Run Code Online (Sandbox Code Playgroud)
rounds 服务中的 Get 方法可以返回 null 并转换为 HTTP 204 No Content。我想知道当我得到空值时如何返回 404:
[HttpGet()]
public ActionResult<Round> Get(string id) =>
this._roundsService.Get(id) ?? NotFound();
Run Code Online (Sandbox Code Playgroud)
显然这不起作用并给我一个 CS0019 错误: Operator '??' cannot be applied to operands of type 'Round' and 'NotFoundResult'
我对其他单行程序持开放态度,如果不为空则返回所需的对象,如果为空则返回 404。
我将 C# 8.0 与 netcoreapp3.0 框架一起使用。我还没有启用可为空功能。这可能是导致问题的原因吗?
以防万一,这里是服务类中的方法:
public Round Get(string id) =>
this._rounds.Find(round => round.Id == id).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
当您调用时NotFound(),您正在创建一个NotFoundResult. 您的方法的返回类型为 ,ActionResult<Round>但NotFoundResult实际上并未从 继承ActionResult<Round>,因此您不能NotFoundResult直接返回对象。
当你做类型return NotFound()则实际发生的事情是,编译器将使用隐式的操作ActionResult<T> (ActionResult)来改造NotFoundResult成一个ActionResult<Round>。
这在您直接返回值时工作正常,但在三元条件或空合并表达式中使用时将不起作用。相反,您必须自己进行转换:
public ActionResult<Round> Get(string id) =>
this._roundsService.Get(id) ?? new ActionResult<Round>(NotFound());
Run Code Online (Sandbox Code Playgroud)
因为 的构造函数ActionResult<T>接受 any ActionResult,您可以将 传递NotFoundResult给它以确保它被正确转换。
当然,您也可以将其再次拆分并让编译器为您进行转换:
public ActionResult<Round> Get(string id)
{
var result = this._roundsService.Get(id);
if (result != null)
return result;
return NotFound();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
522 次 |
| 最近记录: |