简体   繁体   English

属性是[必需]和可空的是什么意思?

[英]What does it mean for a property to be [Required] and nullable?

What does it mean for a property to be [Required] and nullable? 属性是[Required]和可空的是什么意思? (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]它可能不是null (没有值),并且如果它能够为null则它可能不是[Required]

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

The reason for making a property nullable and marked with the [Required] attribute is to protect against under-posting attacks. 使属性可为空并使用[Required]属性标记的原因是为了防止欠发布攻击。 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. 这通常使用视图模型中的值类型属性来完成。

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. 如果属性是DateTime (不可为空),则DefaultModelBinder将初始化其默认值( 01/01/0001 ),并且不会生成ModelState错误。 As a result, that value may then be saved even though its not what you may be expecting. 结果,即使它不是您所期望的,也可以保存该值。

If the property is DateTime? 如果属性是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. (可空)和[Required] ,然后如果恶意用户确实省略了请求中的属性,那么将生成ModelState错误,因为请求中有一个值,并且将返回视图,因此无效数据将不会得救

Refer also Brad Wilson's article Input Validation vs. Model Validation in ASP.NET MVC and the section titled The "Under-Posting" Problem . 另请参阅Brad Wilson 在ASP.NET MVC中的文章输入验证与模型验证以及标题为“欠发布”问题的部分

It's nullable so the form doesn't display an initial value like 0001-01-01T00:00:00 that has no meaning. 它可以为空,因此表单不会显示像0001-01-01T00:00:00这样没有意义的初始值。

It's required to force the user to enter something. 需要强制用户输入内容。

Required is a data annotation for the view. 必需是视图的数据注释。 The view will require it to have a value prior to accepting a form post. 该视图将要求它在接受表单帖子之前具有值。

That the value is nullable is related to what is allowed in the database. 值可以为空可与数据库中允许的内容相关。 A value may be null in the database, or the value may be persisted as null. 数据库中的值可以为null,或者值可以保持为null。

They are separate aspects. 它们是不同的方面。

它是客户端验证所required ,但对于数据库映射是nullable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM