简体   繁体   English

如何在Web API中的模型中禁用属性的必填属性?

[英]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. 如何禁用已在模型属性上设置的[Required]属性。

I tried with below code using new keyword but not working. 我尝试使用下面的代码使用new关键字,但是不起作用。

I also tried override keyword as well not worked. 我也尝试了override关键字,以及它不起作用。

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. ChildModel使用大部分的属性BaseModel这不是创造新的模型文件和代码许多相似的性质,我想着做这样的事情的。

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. 简单地使用属性上的new关键字覆盖或重新声明并删除属性是行不通的。 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. 如果您想了解有关继承期间如何处理基类的属性的更多信息,可以阅读线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将条件必需属性放入类属性中以使用 WEB API? - How to put conditional Required Attribute into class property to work with WEB API? 如何使用 C# 中的属性禁用 model 的属性? - How to disable property of model with the attribute in C#? 如何创建所需的DateTime模型属性? - How can I make a DateTime model property required? 在ASP.NET Web API中禁用模型验证[必需] - Disable Model Validation [Required] in ASP.NET Web API Return BadRequest with null required property in model .net core web api - Return BadRequest with null required property in model .net core web api 是否可以覆盖模型中属性的必需属性? - Is it possible to override the required attribute on a property in a model? 如何在Web API中验证此无效属性? - how can I validate this invalid property in web api? 如何禁用特定 ASP.NET Core 5.0 Web ZDB974238714CA8DE6347A 操作的自动 model 绑定? - How do I disable automatic model binding for a specific ASP.NET Core 5.0 Web API action? 如何在自定义.NET Web控件中指定必需属性? - How do I specify a required attribute in a custom .NET Web control? 我可以将Model属性用作Range验证属性的一部分 - Can I use a Model property as part of a Range validation attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM