3

有了這個代碼:如何安全地處理無效的資料庫數據請求?

public String Get(int id) 
{ 
     return platypi.Find(p => p.Id == id).Name; 
} 

...我可以通過獲取現有的數據:

http://localhost:33181/api/DPlatypus/N 

(其中,N對應於現有ID)。如果我使用一個不存在的價值,但它爆炸了。

所以,我嘗試這樣做:

public String Get(int id) 
{ 
    if (!string.IsNullOrEmpty(platypi.Find(p => p.Id == id).Name)) 
    { 
     return platypi.Find(p => p.Id == id).Name; 
    } 
    return string.Empty; 
} 

...但它沒有有利的影響。有沒有辦法安全地忽略無效請求?

+1

「它吹起來」不提供足夠的細節完全的幫助你了... –

+1

是否在尋找「炸燬」?或名稱? – paqogomez

回答

3

你應該比這更防守。檢查null第一..否則,你問它炸掉:

var entity = platypi.Find(p => p.Id == id); 

return entity == null ? string.Empty : entity.Name; 

你也正在做多單查詢..這你不需要(Find檢查名字..然後Find返回名稱..)。

3

如果Find方法引發異常,則可以將其封裝在異常處理程序中。這將允許你「安全地」在無效輸入上返回一個空字符串。

如果Find回報null,你可以這樣做:

public String Get(int id) 
{ 
    var item = platypi.Find(p => p.Id == id); 

    return item == null ? string.Empty : item.Name; 
}