Net Core:对于非空数据类型,自动在Request API中强制要求的类成员

问题描述

我们有API控制器,可通过请求Dto获取产品数据。为了使类成员成为必需,我们需要在Dto中放置<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- MyAd --> <ins class="adsbygoogle" style="display:inline-block;width:320px;height:60px" data-ad-client="xxxxxxxxx" data-ad-slot="xxxxxxxx"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> 属性。否则,服务可以使用空成员执行。

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1

当前拥有20个以上成员的Request DTO,并且在所有类成员中写Required似乎很重复。

我的问题是,为什么RequiredAttribute是必需的?我们已经有int和nullable成员。数据类型本身不应该执行合同吗?

有没有一种方法可以使类成员自动化并强制执行Required,而无需到处编写?

[Required]

How to add custom error message with “required” htmlattribute to mvc 5 razor view text input editor

[HttpPost]
[Route("[action]")]
public async Task<ActionResult<ProductResponse>> GetProductData(BaseRequest<ProductRequestDto> request)
{
    var response = await _productService.GetProductItem(request);
    return Ok(response);


public class ProductRequestDto
{
    public int ProductId { get; set; }
    public bool Available { get; set; }
    public int BarCodeNumber{ get; set; }
    ....

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)