我怎样才能安全地处理了库数据无效的请求? [英] How can I safely handle invalid requests for repository data?

查看:166
本文介绍了我怎样才能安全地处理了库数据无效的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了这个code:

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

...我可以通过获得现有数据:

...I can get existing data via:

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

(其中,N对应于一个已有的ID)。如果我使用一个不存在的价值,但是,它炸毁。

(where N corresponds to an existing ID). If I use a nonexistent value, though, it blows up.

所以,我想这样的:

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;
}

...但它没有有益效果。有没有办法安全地忽略无效的请求?

...but it has no beneficial effect. Is there a way to safely ignore invalid requests?

推荐答案

您应该远不止于此防守。检查第一..否则你要求它炸掉:

You should be much more defensive than that. Check for null first.. otherwise you're asking for it to blow up:

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

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

你也正在做多单查询更多..你不需要(查找来检查名字..然后查找返回名字..)。

You're also currently doing more than a single lookup.. which you don't need (Find to check name.. then Find to return name..).

这篇关于我怎样才能安全地处理了库数据无效的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆