如何使用空合并运算用的ActionResult ASP.NET 2.1的核心

问题描述 投票:1回答:2

有人可以解释我为什么,我对下面的方法空 - 结合得到一个错误:

private readonly Product[] products = new Product[];

[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
    var product = products.FirstOrDefault(p => p.Id == id);
    if (product == null)
        return NotFound(); // No errors here
    return product; // No errors here

    //I want to replace the above code with this single line
    return products.FirstOrDefault(p => p.Id == id) ?? NotFound(); // Getting an error here: Operator '??' cannot be applied to operands of type 'Product' and 'NotFoundResult'
}  

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

我不明白的是为什么第一个回报没有任何投的需求,而单Seconde系列行空凝聚不工作的工作!

我针对ASP.NET 2.1的核心


编辑:谢谢@Hasan@dcastro的解释,但我不建议使用空合并在这里作为NotFound()投后,将不会返回正确的错误代码!

return (ActionResult<Product>)products?.FirstOrDefault(p => p.Id == id) ?? NotFound();

c# asp.net-core asp.net-core-2.1 null-coalescing
2个回答
1
投票
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public ActionResult<Product> GetById(int id)
{
    if (!_repository.TryGetProduct(id, out var product))
    {
        return NotFound();
    }

    return product;
}

在上面的代码中,当产品不存在于数据库中返回404个状态码。如果产品确实存在,则返回相应的产品对象。 ASP.NET 2.1的核心,退回的产品之前,行会一直返回OK(产品);.

正如你可以从上面从微软的相关page代码和解释看,后.NET 2.1的核心,你并不需要在控制器(ActionResult<T>)返回的确切类型像以前一样。要使用该功能,您需要添加属性,表示可能反应类型,如[ProducesResponseType(200)]等。

在你的情况,你需要做的基本上是添加appropiate响应类型什么属性到控制器方法类似如下所示(因为你使用.NET 2.1的核心开发)。

[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public ActionResult<Product> GetById(int id)

编辑:

为什么你不能编译程序(使用空合并运算符)的原因是,返回类型不competible。在一种情况下,它返回的产品类别,否则返回ActionResult<T>。更新代码,我建议之后,我想你将能够使用空合并运算符。

2.编辑(在这里得到解答)

更深入地挖掘了这个问题之后,我发现使用三元的时候,如果陈述或空合并运算符,我们需要明确指定我们希望从该语句时产生的多种可能,可能会返回什么类型。作为here问过,编译器并不能决定它返回一个类型毫不隐晦地浇铸。所以铸造返回类型的ActionResult解决了这个问题。

return (ActionResult<Product>) products.FirstOrDefault(p=>p.id ==id) ?? NotFound();

但最好如上图所示添加响应类型的属性。


1
投票

发生错误,因为这是不可能投类型。

尝试这个:

[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
    var result = products?.FirstOrDefault(p => p.Id == id);
    return result != null ? new ActionResult<Product>(result) : NotFound();
}
© www.soinside.com 2019 - 2024. All rights reserved.