属性为 [Required] 且可为 null 是什么意思? [英] What does it mean for a property to be [Required] and nullable?

查看:31
本文介绍了属性为 [Required] 且可为 null 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

属性为 [Required] 并且可以为 null 是什么意思?(下面的例子)似乎如果它是 [Required] 它不可能是 null (没有值),如果它能够是 null 不可能是[Required].

What does it mean for a property to be [Required] and nullable? (example below) It seems that if it is [Required] it couldn't possibly be null (no value), and if it is able to be null it couldn't possibly be [Required].

[Required]
public DateTime? OrderDate { get; set; }

推荐答案

使属性可以为空并用 [Required] 属性标记的原因是为了防止发布不足的攻击.它还允许您在视图中显示初始空值而不是属性的默认值.这通常通过视图模型中的值类型属性来完成.

The reason for making a property nullable and marked with the [Required] attribute is to protect against under-posting attacks. It also allows you to display an initial empty value in the view rather than the default value for the property. This is typically done with value type properties in view models.

发布不足攻击是指恶意用户修改请求以省略请求中属性的值.如果属性是 DateTime(不可为空),则 DefaultModelBinder 将初始化该值的默认值 (01/01/0001) 并且没有 ModelState 会产生错误.因此,即使该值不是您所期望的,也可能会被保存.

An under-posting attack is where a malicious user modifies the request to omit a value for the property in the request. If the property was DateTime (not nullable), then the DefaultModelBinder will initialize the value its default (01/01/0001) and no ModelState error would be generated. As a result, that value may then be saved even though its not what you may be expecting.

如果属性是DateTime?(可为空)和[Required],那么如果恶意用户确实在请求中省略了该属性,则ModelState 请求中需要一个值会产生错误,会返回视图,因此不会保存无效数据.

If the property is DateTime? (nullable) and [Required], then if a malicious user did omit the property in the request, then a ModelState error will be generated because a value is expected in the request, and the view would be returned, therefore the invalid data will not be saved.

另请参阅 Brad Wilson 的文章 ASP.NET MVC 中的输入验证与模型验证 以及标题为Under-Posting"问题的部分.

Refer also Brad Wilson's article Input Validation vs. Model Validation in ASP.NET MVC and the section titled The "Under-Posting" Problem.

这篇关于属性为 [Required] 且可为 null 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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