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

时间:2017-01-04 10:18:36

标签: c# asp.net web-services rest asp.net-web-api

我有一个问题,即在webapi中返回数据的最佳方法是什么。 例如,我们可以有2个场景。

  

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

     

2)我们返回数据列表的GetProducts

所以对于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);
    }

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

我建议制作一个包含您自己的codemessageresponse object的通用对象:

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

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

相关问题