【问题标题】:What is the recommended way to respond to bad user input with a REST API?使用 REST API 响应不良用户输入的推荐方法是什么?
【发布时间】:2016-12-25 05:07:38
【问题描述】:

假设如下:

  • 我有一个会返回水果名称的 rest API,而且只有 5 个水果。
  • 要获得水果名称,我必须申请一个 ID。

考虑以下代码:

public class Fruit {
    public int FruitID { get; set; }
    public string FruitName { get; set; }
    public Fruit(string json){
        JObject o = JObject.Parse(json);
        FruitID = Int32.Parse((string) o["id"]);
        FruitName = (string) o["name");
    }
}

public static Fruit getFruit(int id){
    Task<Fruit> task = "http://fruit.com/get_fruit"
        .SetQueryParams(new { fruit_id = id })
        .GetStringAsync();
    return new Fruit(task.Result);
}

(如果此时有任何问题,请纠正我,我是 C# 任务的新手)

假设当该任务返回时,如果它收到一个有效的 ID,则 json 可能如下所示...

{
    "status":1,
    "id": 3,
    "name": "apple"
}

或者,如果它收到无效的 ID。

{
    "status":0
}

如果用户应该输入要搜索的 ID,那么他们有可能输入一个不存在的 ID,因为只有 5 个(0 到 4)。根据我上面输入的代码,如果返回 "status":0,我可以看到应用程序崩溃,因为它没有类构造函数正在寻找的两个字段。

我的问题是:处理可能的无效输入(例如用户输入的 ID 为 20)的最佳方法是什么?

【问题讨论】:

    标签: c# json rest xamarin


    【解决方案1】:

    RESTful API 的推荐方法是使用 HTTP 错误代码,在您的情况下为 404(未找到),因为请求的水果不存在。 您应该在尝试创建对象之前处理错误代码。所以检查请求是否已经成功执行(200 OK),然后处理payload。

    以下是状态码参考: http://www.restapitutorial.com/httpstatuscodes.html

    【讨论】:

    • 我知道你来自哪里,除了我使用的 API 不返回 404。它返回一个"status":0。我可以和 API 经理谈谈。
    • 这个想法是相似的,你应该在实体之前处理状态。在该示例中,检查状态是否为“1”,然后解析 Fruit,否则处理错误状态 (0)
    【解决方案2】:

    输入验证是 Web 服务开发中的重要任务之一。我个人有两个阶段。首先我检查对象的空值。为了做到这一点,我编写了这个方法:

    private bool HasNull(object webServiceInput, string[] optionalParameters = null)
    {
    
        if (ReferenceEquals(null, webServiceInput))
            return false;
    
        if (optionalParameters == null)
            optionalParameters = new string[0];
    
        var binding = BindingFlags.Instance | BindingFlags.Public;
        var properties = webServiceInput.GetType().GetProperties(binding);
        foreach (var property in properties)
        {
            if (!property.CanRead)
                continue;
    
            if (property.PropertyType.IsValueType)
                continue;
    
            if (optionalParameters.Contains(property.Name))
                continue;
    
            var value = property.GetValue(webServiceInput);
            if (ReferenceEquals(null, value))
                return false;
        }
    
        return true;
    }
    

    然后,如果某些输入应该具有指定的验证,我会单独检查它。例如,我检查 ID 是否在 0 到 5 之间; 希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2020-04-30
      • 2014-01-21
      • 2023-03-06
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2016-09-12
      • 2021-11-16
      • 2019-03-19
      相关资源
      最近更新 更多