簡體   English   中英

如何在 ActionResult ASP.NET Core 2.1 中使用空合並運算符

[英]How to use null-coalescing operator with ActionResult ASP.NET Core 2.1

有人可以解釋一下為什么我在以下方法的空合並上出現錯誤:

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; }
}

我不明白的是為什么第一個返回不需要任何轉換就可以工作,而第二個單行空合並不起作用!

我的目標是 ASP.NET Core 2.1


編輯:感謝@Hasan@dcastro的解釋,但我不建議在此處使用空合並,因為NotFound()在轉換后不會返回正確的錯誤代碼!

發生錯誤是因為無法轉換類型。

嘗試這個:

[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
    var result = products?.FirstOrDefault(p => p.Id == id);
    return result != null ? new ActionResult<Product>(result) : NotFound();
}
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public ActionResult<Product> GetById(int id)
{
    if (!_repository.TryGetProduct(id, out var product))
    {
        return NotFound();
    }

    return product;
}

在前面的代碼中,當數據庫中不存在該產品時,將返回404狀態代碼。 如果產品確實存在,則返回相應的Product對象。 在ASP.NET Core 2.1之前,返回產品; 行應該返回Ok(product);。

從上面的代碼和Microsoft相關頁的說明中可以看到,.NET Core 2.1之后,您無需像以前一樣在控制器中返回確切的類型( ActionResult<T> )。 要使用該功能,您需要添加屬性以指示可能的響應類型,例如[ProducesResponseType(200)]等。

在您的情況下,您需要做的基本上是向控制器方法中添加適當的響應類型屬性,如下所示(因為您是使用.NET Core 2.1開發的)。

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

編輯:

無法編譯程序(使用null運算符)的原因是返回類型不具有競爭力。 在一種情況下,它將返回產品類,否則將返回ActionResult<T> 按照我的建議更新代碼后,我想您將可以使用null-coalescing運算符。

2.編輯 (在此處回答)

在更深入地研究問題之后,我發現當使用三元if語句或null合並運算符時,當可能返回多種類型時,我們需要明確指定期望從該語句中生成哪種類型。 如前問這里 ,編譯器並不能決定它返回一個類型毫不隱晦地澆鑄。 因此,將返回類型強制轉換為ActionResult即可解決問題。

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

但是最好添加響應類型屬性,如上所示。

OP 的問題可以分為兩部分:1) 為什么建議的空合並表達式不能編譯,以及 2) 在 ASP.NET Core 2.1 中是否有另一種簡潔的(“單行”)方式返回結果?

如@Hasan 答案的第二次編輯所示, 空合並運算符的結果類型是根據操作數類型而不是目標類型來解析的。 因此,OP 的示例失敗了,因為ProductNotFoundResult之間沒有隱式轉換:

products.FirstOrDefault(p => p.Id == id) ?? NotFound();

@Kirk Larkin 在評論中提到了一種在保持簡潔語法的同時修復它的方法:

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

從 C# 8.0 開始,您還可以使用switch 表達式

products.FirstOrDefault(p => p.Id == id) switch { null => NotFound(), var p => p };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM