首页 > 解决方案 > datatype.text 验证什么?

问题描述

我有一个生产应用程序在我们的CWE-100安全扫描中受到打击。我知道这是一个已弃用的项目,但它仍然显示在我的报告中。

目前我只看到两个要采取的行动,

  1. 处理好每一项,清除报告上的瑕疵
  2. 标记缺陷并评论它已被弃用,然后与我的安全团队交谈。

关于修复它,我发现向变量添加数据类型属性删除了警告。这是我已修复的片段

[DataType(DataType.Text)]
public string Name { get; set; }
...
[DataType(DataType.Text)]
[Required(ErrorMessage = "Please enter documentation.")]
public string Documentation{ get; set; }

我找不到任何来自 Microsoft 的关于此数据类型属性验证的文档。如果确实如此,从一些小测试中,我仍然可以将我复制的任何字符输入到为此显示的文本框中。

是否有理由添加此属性,或者我会浪费我的时间?

标签: asp.net-mvcvalidation

解决方案


免责声明:这只是我阅读源代码的理解(请随时纠正我)

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.TimeDataType.Currency... 添加一些格式(同时设置_dataTypeStrings

此外,您还有验证属性,例如EmailAddressAttributePhoneAttributeUrlAttribute等,这些属性派生自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不会增加任何价值,最好不要使用它来保持代码更小、更清晰、更易于理解......


推荐阅读