C# 在webapi中返回数据的最佳方式是什么

C# 在webapi中返回数据的最佳方式是什么,c#,asp.net,web-services,rest,asp.net-web-api,C#,Asp.net,Web Services,Rest,Asp.net Web Api,我有一个问题,在webapi中返回数据的最佳方式是什么。 对于eg,我们可以有两种场景 1) GetProductsById,我们在其中接收id并返回该id的数据 2) 获取返回数据列表的产品 因此,对于GetProductsById,我们可以执行以下操作: public IHttpActionResult GetProduct(int id) { var product = getProducts().FirstOrDefault((p) => p.Id ==

我有一个问题,在webapi中返回数据的最佳方式是什么。 对于eg,我们可以有两种场景

1) GetProductsById,我们在其中接收id并返回该id的数据

2) 获取返回数据列表的产品

因此,对于GetProductsById,我们可以执行以下操作:

 public IHttpActionResult GetProduct(int id)
    {
        var product = getProducts().FirstOrDefault((p) => p.Id == id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
要获取列表,请执行以下操作:

 public IHttpActionResult GetProduct(int id)
    {
        var products = getproducts();
        if (products == null)
        {
            throw new NotFoundException()
        }
        return Ok(product);
    }

我想知道在这两种情况下处理未找到场景的最佳方法。

在这两种情况下,我都会返回错误消息的错误请求

public IHttpActionResult GetProduct(int id){ var products = getproducts(); if (products == null) { BadRequest("Item not found.") } return Ok(product); }

我建议创建一个通用对象,它可以保存您自己的
code
消息
、和
响应对象
,如下所示:

 [Serializable]
[DataContract]
public class ApiResponse
{
    [DataMember]
    public int code;
    [DataMember]
    public string message;
    [DataMember]
    public dynamic result;
}

结果保存您的实际结果,其中代码和消息根据您的数据验证进行定制。

最好的方法是在这种情况下应用程序的其余部分已经执行的任何操作。您的问题是基于意见的,不符合主题。在这种情况下,应该是
NotFound
exception,而不是
BadRequest