json - 为什么 postman 中显示 "The field is required",即使它可以为空?

标签 json asp.net-core entity-framework-core postman repository-pattern

我已将我的 asp.net core 项目连接到 MS SQL Server,并在编写 Controller 后尝试测试我的 API。以下是我尝试使用的 2 个数据模型。

 public partial class Content
    {
        public Guid CCuid { get; set; }
        public Guid CPuid { get; set; }
        public string? CContents { get; set; }
        public decimal? CAmount { get; set; }
        public string? CCheckNumber { get; set; }
        public int? CQuantity { get; set; }
        public string? CNotes { get; set; }
        public DateTime CDateProcessed { get; set; }
        public string? CUserName { get; set; }
        public virtual Vompackage? CPu { get; set; } 
    }


 public partial class Package
      {
        public Package()
        {
            Contents = new HashSet<Content>();
        }
    
        /// <summary>
        /// Unique Package Identifier
        /// </summary>
        public Guid PPuid { get; set; }
        public Guid PSuid { get; set; }
        public string? PTrackingNumber { get; set; }
        public string? PBolnumber { get; set; }
        public string? PProductCode { get; set; }
        public int? PQuantity { get; set; }
        public int? PPallets { get; set; }
        public int? PBoxes { get; set; }
        public string? PNotes { get; set; }
        public DateTime PDateEntered { get; set; }
    
        public virtual Vomshipment? PSu { get; set; }
        public virtual ICollection<Content> Contents { get; set; }
    }
    }

现在我正在尝试使用 postman 添加内容。当我尝试添加以下数据时,

{
    "cAmount": 2332,
    "cCheckNumber": "",
    "cQuantity": 133,
    "cNotes": "thank u ",
    "cDateProcessed": "2020-12-02T13:40:47.207",
    "cUserName": "ztinsley",
    "CPu": null
    }
         

它给出 400 响应,并且

"errors": {
    "CPu": [
        "The CPu field is required."
    ]

我使用 null! 使 CPu 可为空。当我测试 GET 方法来提取所有内容时,它对每个数据都显示 "cPu": null 。为什么添加新数据时遇到问题?我还尝试在 AddControllers() 中添加 options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true ,但它给了我 500 响应。请帮忙!

附注 我已连接 Controller 以查看是否犯了任何错误。

   [Produces("application/json")]
        [ApiController]
        [Route("api/content")]
        public class ContentController : Controller
        {
            private readonly IContentRepository _contentReporitory;
    
            public ContentController(IContentRepository contentReporitory)
            {
                _contentReporitory = contentReporitory;
            }
   [HttpGet("{ccuid}")]
        public async Task<ActionResult<Content>> GetContentById(Guid ccuid)
        {
            try
            {
                var result = await _contentReporitory.GetContentById(ccuid);

                if (result == null)
                {
                    return BadRequest();
                }

                return result;
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError,
                    "Error retrieving data from the database");
            }
        } 
            [HttpPost("addcontent")]
            public async Task<ActionResult<Content>> AddContent([FromBody]Content content)
            {
                try
                {
                    if (content == null)
                        return BadRequest();
    
                    var newContent = await _contentReporitory.AddContent(content);
    
                    return CreatedAtAction(nameof(GetContentById),
                        new { id = newContent.CCuid }, newContent);
    
    
                } catch (Exception)
                {
                    return StatusCode(StatusCodes.Status500InternalServerError);
                }
            }
    
        }
    }

我的存储库:

    public class ContentRepository : IContentRepository
    {
        private readonly OperationsContext _operationsContext;

        public ContentRepository(OperationsContext operationsContext)
        {
            _operationsContext = operationsContext;
        }

        public async Task<Content> AddContent(Content content)
        {
            var result  = await _operationsContext.Contents.AddAsync(content);
            await _operationsContext.SaveChangesAsync();
            return result.Entity;
        }


    }
}

最佳答案

以 .NET 6 (C# 10) 开头的所有项目模板都为项目启用可为空上下文。使用早期模板创建的项目不包含此元素,并且除非您在项目文件中启用它们或使用编译指示,否则这些功能将被关闭。这意味着 CPu 被视为不可为 null 的属性。

因此您只需发送 {} 而不是 null:

{
    "cAmount": 2332,
    "cCheckNumber": "",
    "cQuantity": 133,
    "cNotes": "thank u ",
    "cDateProcessed": "2020-12-02T13:40:47.207",
    "cUserName": "ztinsley",
    "CPu": {}
    }

或者直接设置

public virtual Package? CPu { get; set; } 

然后您可以发送"CPu": null

可以引用这个Docs了解更多信息。

关于json - 为什么 postman 中显示 "The field is required",即使它可以为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73695690/

相关文章:

c# - 带有 System.Text.Json 的可选属性的自定义 JSON 序列化程序

objective-c - cocoa :如何将 NSAttributedString 保存到 JSON

javascript - JSON 数据不会通过 jQuery getJSON() 显示

c# - onclick 方法在 Blazor 服务器端 Razor 组件中不起作用

c# - 如何替换 AutoMapper 9.0 中的 `AutoMapper.Mapper.Initialize` 静态调用?

mariadb - Entity Framework Core 是否支持 MariaDB?

c# - 使用连接字符串 Entity Framework 在运行时生成 DbContext 和模型

python - JSON 格式的 "TypeError: list indices must be integers, not str"

msbuild - 无法在构建服务器上发布 ASP.NET Core 1.0 RC2 应用程序

c# - include 中的动态查询过滤器表达式