使用这段代码:
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;
}
...但它没有任何有益效果。有没有办法安全地忽略无效请求?
最佳答案
你应该比那更具防御性。首先检查 null
.. 否则你要求它爆炸:
var entity = platypi.Find(p => p.Id == id);
return entity == null ? string.Empty : entity.Name;
您目前还不止一次进行查找.. 您不需要(Find
来检查名称.. 然后 Find
返回名称.. ).
关于c# - 如何安全地处理对存储库数据的无效请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21125722/