2016-12-25 24 views
0

假設如下:使用REST API響應不良用戶輸入的建議方式是什麼?

  • 我休息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#任務)

比方說,當任務返回時,JSON可能看起來像以下,如果它收到一個有效的ID ...

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

或者這是否收到無效ID。

{ 
    "status":0 
} 

如果假設用戶輸入中搜索其ID,然後有一個機會,他們可以輸入一個不存在的ID,因爲只有5,(0到4)。根據我上面輸入的代碼,如果返回"status":0,我可以看到應用程序崩潰,因爲它沒有類構造函數正在查找的兩個字段。

我的問題是:處理可能的無效輸入(例如用戶輸入20的ID)的最佳方法是什麼?

回答

2

RESTful API的推薦方式是使用HTTP錯誤代碼,在你的情況下它會是404(未找到),因爲請求的水果不存在。 在嘗試創建對象之前,您應該處理錯誤代碼。因此請檢查請求是否已成功執行(200 OK),然後處理有效負載。

這裏的狀態代碼的參考: http://www.restapitutorial.com/httpstatuscodes.html

+0

我看到你來自哪裏,除了我使用的API不返回404的。它返回一個''狀態':0'。我可以與API經理談談。 – Hidden14

+0

這個想法雖然相似,但你應該在實體之前處理狀態。在這個例子中,檢查狀態是否爲「1」,然後解析Fruit,否則處理錯誤狀態(0) –

0

輸入驗證是在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之間; 我希望它能幫助你。

相關問題