简体   繁体   中英

How can I disable required attribute on a property in a model in web api?

How to disable the [Required] attribute that has been set on a model property.

I tried with below code using new keyword but not working.

I also tried override keyword as well not worked.

ChildModel uses most of the properties of BaseModel that's instead of create new model file and code many similar properties I'm thinking to do something like this.

public class BaseModel
{
    [Required]
    public string Address{ get; set; }
}


public class ChildModel : BaseModel
{
    public new string Address{ get; set; }    
}

Any simple solution ?

Simply overriding or redeclaring using the new keyword on the property and removing the attribute does not work. The way I have always done this is like below.:

public abstract class BaseModel
{
    public abstract string Address { get; set; }
}


public class ChildModel : BaseModel
{
    [Required]
    public override string Address { get; set; }
}

public class AnotherChildModel : BaseModel
{
    //Not[Required]
    public override string Address { get; set; }
}

You can read this thread if you want to know more on how attributes of a base class are treated during inheritance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM