gpt4 book ai didi

c# - Asp.net-MVC 自定义验证 - NULL 与空

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:58 32 4
gpt4 key购买 nike

为了安全性和一致性,如果缺少某个字段,我想在回发时进行测试?在 Java(尤其是 servlet)中,当我们执行 request.getParameter(key) 时,结果要么是一个 String 值,要么是 NULL(如果该字段缺失)。在 MVC 中,我创建了一个自定义验证,我称之为“ThrowOnNull”。我试图捕获的行为是:如果缺少预期的字段(null),我想抛出,否则返回成功。

考虑这个自定义验证器(它不起作用):

public class ThrowOnNull: ValidationAttribute
{
public ThrowOnNull() { }

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
throw new Exception(validationContext.MemberName + " field expected, but missing."));

return ValidationResult.Success;
}
}

这里可以做我想做的事吗?(这个验证器没有按预期工作,这是因为框架正在将 NULL 分配给一个空值 [哦,亲爱的]。)

更新:根据@emodendroket,以下代码示例现在可以按预期工作:

public class ThrowOnMissing: ValidationAttribute
{
public ThrowOnMissing() { }

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!HttpContext.Current.Request.Form.AllKeys.Contains(validationContext.MemberName))
throw new Exception(validationContext.MemberName + " field expected, but missing.");

return ValidationResult.Success;
}
}

编辑:我已经显着清理了问题和示例代码以使其更加清晰,希望它有所帮助。

最佳答案

您遗漏了一个重点 - 当您提交表单时,属于该表单的所有字段都会被提交。如果用户不填写它们,它们就是空白,因此 null 的验证不能真正像这样工作......

您可能应该重新定义“缺失值”的含义。

编辑:
经过一番讨论后,您似乎并不真正关心空值,而是关心安全性(缺少字段的虚假表格和类似的东西)。在那种情况下,您应该简单地使用标准 - 防伪 token ,并可能检查请求的来源。你应该这样就好了。检查丢失的字段也无济于事,因为攻击者也可以轻松发送这些字段。

Over/Under posting is a real concern. Furthermore, if fields aren't submitted (due to a hack or DOS attack of some kind)

不是真的。

过度发布由 Controller 上的操作方法处理。它不会接受比您指定的更多的参数。

Underposting 的处理方式与您没有填写表单中的文本字段的处理方式几乎相同,如果您正确验证了模型,这同样不是问题。

DDOS 攻击是无法阻止的,相信我,如果某人的网络强大到足以引发 DDOS,一些检查缺失字段的方法将无济于事。看看最新的攻击案例你就会明白,如果HUGE服务器不能承受,你肯定不能这样阻止。

您的数据验证也不应该太昂贵。这是一个网络,人们不喜欢等待太多。

关于c# - Asp.net-MVC 自定义验证 - NULL 与空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655084/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com