雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

ASP.NET Core 2.1中的ActionResult<T>

2024-10-16 11

ASP.NET Core 2.1的一个新功能是,一个名为ActionResult<T>的新类型,它允许您返回响应类型或任何操作结果,同时仍然指示响应类型。在这篇短文中,我们将看到如何使用ASP.NET Core 2.1中的新型ActionResult<T>,以及它解决了什么问题。

下面是一段非常熟悉的API操作代码。

public Product Get(int id)
{
    Product prod = null;
    // TODO: Get product by Id
    return prod;
}

在这里,我们按ID搜索产品并返回搜索的产品。API操作方法的返回类型是产品,它有助于API文档以及客户机了解预期的响应。但是,这个代码有一个问题,因为当没有针对ID的产品时,这个代码将失败。修复也很简单。

public ActionResult Get(int id)
{
    Product prod = GetProduct(id);
    if(prod == null)
    {
        return NotFound();
    }
    return ok(prod);
}

很好,但是API操作方法签名现在不再指示返回对象的类型。ASP.NET Core 2.1中的新类型ActionResult<T>解决了这个问题。

在ASP.NET Core 2.1中,我们可以用以下方法使用ActionResult<T>编写上述代码。

public ActionResult<Product> Get(int id)
{
    Product prod = GetProduct(id);
    if(prod == null)
    {
        return NotFound();
    }
    return prod;
}

在这里,ActionResult将在运行时基于结果返回产品对象或ActionResult。

更新于:2天前
赞一波!

文章评论

评论问答