对DTO的验证

时间:2015-06-16 07:28:43

标签: c# validation dto

我正在使用Business Objects层,服务层和Web层在MVC中开发三层架构 业务对象层包含DTO(数据传输对象) 服务层处理DTO并包含业务逻辑 我的一个DTO如下:

 public class InsertCompanyGroupDto
{
    public InsertCompanyGroupDto()
    {
        this.CompanyGroupAddressDetails = new InsertAddressDto();
    }
    public InsertAddressDto CompanyGroupAddressDetails { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
    [StringLength(100, ErrorMessage = "The {0} can not exceed {1} characters long.")]
    public string CompanyGroupName { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
    [StringLength(200, ErrorMessage = "The {0} can not exceed {1} characters long.")]
    public string SiteUrl { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
    [StringLength(20, ErrorMessage = "The {0} can not exceed {1} characters long.")]
    public string UserNameTag { get; set; }
}

在此代码中,我在Insert Company Group DTO中使用InsertAddressDto 两者都有验证。请查看插入地址DTO。

public class InsertAddressDto
{
    [Min(1, ErrorMessage = "{0} should be minimum of {1}.")]
    [Required(ErrorMessage = "The {0} is required.")]
    public short AddressTypeId { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is required.")]
    [StringLength(100, ErrorMessage = "The {0} can not exceed {1} characters long.")]
    public string Address1 { get; set; }

    [StringLength(100, ErrorMessage = "The {0} can not exceed {1} characters long.")]
    public string Address2 { get; set; }
}

从上面的代码中,我只传递一个请求作为JSON,其中包含

{
"CompanyGroupName":"CG5",
"SiteUrl":"http://localhost:33570/MultiChoice5",
"UserNameTag":"Aker1",
"SourceCode":"Test22",
"PageFooter":"test22",
"CreatedById":"1",
"AddressTypeId":"6",
"Address1":"test 1",
"Town":"testt",
"Postcode":"24234",
"CountryId":"1",
"CreatedById":"1"
}

我在DTO中使用以下代码进行验证。

public IEnumerable<ValidationResult> Validate()
    {
        return Validate(new ValidationContext(this));
    }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        Validator.TryValidateObject(this, validationContext, results, true);

        return results;
    }

我在两个DTO(公司组和地址)中使用此代码 验证仅适用于InsertCompanyGRoupDTO,但不适用于InsertAddressDTO 我怎样才能纠正这个问题? 我需要知道如何同时验证两个DTO(一个在另一个内)?

0 个答案:

没有答案