【发布时间】:2020-02-08 20:38:25
【问题描述】:
我正在 linux(pop os) 中构建一个简单的 Asp.Net Core 应用程序。我正在使用 VueJs + Aps.Net Core 3.1.101 我正在尝试对我的应用进行 POST 调用,我的模型如下所示:
public class AddConfigurationContextValueApiRequest
{
public int ContextId { get; set; }
[Required(ErrorMessage = "Value is required to continue")]
[StringLength(500, ErrorMessage = "Value can not be longer than 500 characters")]
public string Value { get; set; }
[StringLength(500, ErrorMessage = "Display name can not be longer than 500 characters")]
public string DisplayName { get; set; }
}
如您所见,DisplayName 字段没有 Required 属性,但每当我从 VueJS 应用程序为该字段传递 null 值时,我都会得到 The DisplayName field is required.。
我试图弄清楚为什么 AspNet Core 会为此抱怨,因为此类字段没有 Required 属性!
有人知道这是不是故意的吗?我试图删除StringLength 属性,但它仍然触发了必需的属性。
我的操作很简单:
[HttpPost(UrlPath + "addConfigurationContextValue")]
public async Task AddConfigurationContextValue([FromBody]AddConfigurationContextValueApiRequest request)
{
using var unitOfWork = _unitOfWorkProvider.GetOrCreate();
if (!ModelState.IsValid)
{
//Here it throws because ModelState is invalid
throw new BadRequestException(ModelState.GetErrors());
}
//do stuff
await unitOfWork.CommitAndCheckAsync();
}
【问题讨论】:
-
嗯,这很奇怪。快速浏览一下,一切看起来都是正确的。我还可以确认
[StringLength()]属性不应该 暗示[Required]。我有绑定模型,例如[StringLength(250)]未标记为[Required]并通过ModelState.IsValid检查它们是否为null。 -
您是否碰巧启用了 C# 8 Nullable Reference Types 功能?
标签: c# asp.net-core asp.net-core-3.1