【问题标题】:What is Best way to return Data in webapi [closed]在 web api 中返回数据的最佳方式是什么 [关闭]
【发布时间】:2017-05-18 14:23:05
【问题描述】:

我有一个问题,在 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);
    }

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

【问题讨论】:

  • 最好的方法是应用程序的其余部分在遇到这种情况时已经做了什么。您的问题是基于意见和题外话

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


【解决方案1】:

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

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

【讨论】:

  • 在这种情况下应该是NotFound异常而不是BadRequest
【解决方案2】:

我建议制作一个可以容纳您自己的 codemessageresponse object 的通用对象,如下所示:

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

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

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多