asp.net-mvc - datatype.text 验证什么?
问题描述
我有一个生产应用程序在我们的CWE-100安全扫描中受到打击。我知道这是一个已弃用的项目,但它仍然显示在我的报告中。
目前我只看到两个要采取的行动,
- 处理好每一项,清除报告上的瑕疵
- 标记缺陷并评论它已被弃用,然后与我的安全团队交谈。
关于修复它,我发现向变量添加数据类型属性删除了警告。这是我已修复的片段
[DataType(DataType.Text)]
public string Name { get; set; }
...
[DataType(DataType.Text)]
[Required(ErrorMessage = "Please enter documentation.")]
public string Documentation{ get; set; }
我找不到任何来自 Microsoft 的关于此数据类型属性验证的文档。如果确实如此,从一些小测试中,我仍然可以将我复制的任何字符输入到为此显示的文本框中。
是否有理由添加此属性,或者我会浪费我的时间?
解决方案
免责声明:这只是我阅读源代码的理解(请随时纠正我)
(DataTypeAttribute)是一个ValidationAttribute
(派生自ValidationAttribute
),您需要向它传递一个Enum(也称为DataType
)。
Validation Attributes 需要覆盖IsValid
方法,该方法在模型绑定上执行,并且需要确定值是否有效。这是自定义验证器的样子:
public class CustomValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// do some validation
if (/* validation passes */)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Validation message...");
}
}
}
现在,回到DataTypeAttribue
(这是一个验证属性),您需要将它传递给DataType
枚举:
public enum DataType
{
Custom = 0,
DateTime = 1,
Date = 2,
Time = 3,
Duration = 4,
PhoneNumber = 5,
Currency = 6,
Text = 7,
Html = 8,
MultilineText = 9,
EmailAddress = 10,
Password = 11,
Url = 12,
ImageUrl = 13,
CreditCard = 14,
PostalCode = 15,
Upload = 16
}
据我所知,DataTypeAttribtue
所做的只是为DataType.Date
,DataType.Time
和DataType.Currency
... 添加一些格式(同时设置_dataTypeStrings
)
此外,您还有验证属性,例如EmailAddressAttribute、PhoneAttribute、UrlAttribute等,这些属性派生自DataTypeAttribute
这些特定类型并对其进行额外验证:
现在这是您可以使用这些验证属性的方式:
public class MyModel
{
[Phone] // <- executes the IsValid method of PhoneAttribute
public String Home { get; set; }
[DataType(DataType.PhoneNumber)] // <- does NOT execute IsValid method of PhoneAttribute
public String Mobile { get; set; }
[EmailAddress] // <- executes the IsValid method of EmailAddressAttribute
public String Email { get; set; }
[DataType(DataType.Currency)] // <- does the Currency formatting
public decimal Price { get; set; }
[DataType(DataType.Date)] // <- does the Date formatting
public DateTime ReleaseDate { get; set; }
[DataType(DataType.Text)] // <- does NOT add any validation/formatting
public string Name { get; set;}
/*
* this is the only scenario that I can think of, for using: [DataType(DataType.Text)]
*/
[DataType(DataType.Text)]
public object someKey { get; set;}
}
同样,据我所知,添加[DataType(DataType.Text)]
tostring
不会增加任何价值,最好不要使用它来保持代码更小、更清晰、更易于理解......
推荐阅读
- python - 使用循环、元组、列表、字典等的销售计算器
- c# - 使用保存在变量中的类型调用泛型函数
- flask - 在哪里放置 setup.py 文件以使 Flask 项目可安装?
- php - SmartyException 0():Prestashop 缺少“$template”参数
- python - AttributeError:“系列”对象没有属性“上”
- mysql - Mysql 全表更新调整
- java - spring-security-oauth2 中的 Insteate 自定义 OAuth2User 导致反序列化错误
- python - Python - 将函数值转换为 int 或 float 以进行比较
- c++ - 在 C++ 中从 test.txt 中读取信息
- php - 相当于 Openlitespeed 中的 header('X-Accel-Buffering: no') 以禁用输出缓冲?