繁体   English   中英

如何为可枚举类型返回 NotFound()?

[英]How do I return NotFound() for an enumerable type?

我正在尝试为此方法返回 NotFound 但收到此错误:

Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.NotFoundResult' to 'System.Collections.Generic.IEnumerable<myapp.WeatherForecast>'. An explicit conversion exists (are you missing a cast?)

我不明白它应该如何投射。 如果参数等于“1”,我想返回 404。

[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IEnumerable<WeatherForecast> Test(int param)
{
    var rng = new Random();

    if (param == 1)
    {
        // Trying to return NotFound here
        return NotFound();
    }

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}

更新

我只需要这样做: public ActionResult<IEnumerable<WeatherForecast>> Test(int param)

也许我应该关闭它,但现在我仍然对这有什么影响感到困惑。 在我刚刚返回一个枚举之前,现在(如果参数不是 == 1)我将返回一个包含在 actionresult 中的枚举?

IEnumerable<WeatherForecast>更改为IActionResult以便您可以返回 NotFound,

public IActionResult Test(int param)

或者为了类型安全

public ActionResult<IEnumerable<WeatherForecast>>

编辑:

ASP.NET Core 为 Web API 控制器操作返回类型提供以下选项:

 - Specific type - IActionResult - ActionResult<T>

本文档解释了何时最适合使用每种返回类型。

你没有。 您从控制器操作、Razor Page OnGet()或任何其他需要返回IActionResult地方返回NotFound() ,以指示请求应返回 404 not found 错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM