在ASP.NET Web API中禁用模型验证[必需]

时间:2019-03-13 18:39:14

标签: c# asp.net asp.net-web-api model-validation

所以基本上我有两个类,分别是Model和DTO,Model将用于处理API,而DTO将处理数据库(Firestore)。

我有一个 Company 模型,在这种模型中,当我执行CreateCompany POST请求时,必须提供CompanyName。

public class Company
{
    public string CompanyId { get; set; }

    [Required]
    public string CompanyName { get; set; }
}

这是我用来创建员工详细信息的 Employee 模型,该类将使用 Company 模型。

public class Employee
{
    public string EmployeeId { get; set; }

    public bool? IsFirstLogin { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [EmailAddress]
    public string PaypalEmail { get; set; }

    [Required]
    [Phone]
    public string PhoneNumber { get; set; }

    public Company company { get; set; }
}

现在的问题是,当我发出CreateEmployee POST请求时,我只需要填写 Employee.company.CompanyId ,但是因为在公司模型中,是 Company。 CompanyName 之前已设置为[Required],并且必须填写 Employee.company.CompanyName

所以我在考虑是否有任何方法可以在发出CreateEmployee POST请求期间禁用模型验证。还是我应该只在CreateCompany POST请求期间启用模型验证?

2 个答案:

答案 0 :(得分:2)

您可以基于CompanyName是内部属性还是顶级模型来创建验证Company的自定义验证属性

[AttributeUsage(AttributeTargets.Class)]
public class RequierdCompanyNameAttribute: RequiredAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //validate if top level model
        if (validationContext.ObjectType == typeof(Company))
            return base.IsValid(value, validationContext);

        //no validation inside Employee
        return ValidationResult.Success;
    }

    public override bool IsValid(object value)
    {
        Company company = (Company)value;
        //validate CompanyName with RequiredAttribute
        return base.IsValid(company.CompanyName);
    }
}

和用法

[RequierdCompanyName]
public class Company
{
    public string CompanyId { get; set; }

    public string CompanyName { get; set; }
}

但是最简单的方法是为此目的引入不同的模型

public class Company
{
    public string CompanyId { get; set; }

    [Required]
    public string CompanyName { get; set; }
}

public class EmployeeCompany
{
    [Required]
    public string CompanyId { get; set; }

    public string CompanyName { get; set; }
}

public class Employee
{
    //..

    public EmployeeCompany Company { get; set; }
}

答案 1 :(得分:0)

从ModelState删除有问题的属性

ModelState.Remove( “Company.CompanyName” );