属性为[Required]并且可为空意味着什么? [英] What does it mean for a property to be [Required] and nullable?

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

问题描述

属性为[Required]并且可为空意味着什么? (下面的示例)看来,如果它是[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的文章的部分.

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

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

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