首页 > 解决方案 > 字符串字段是必需的。即使你在 Asp.Net Core 中也没有必需的属性?

问题描述

我正在 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; } 
}

如您所见,该字段没有Required属性DisplayName,但是每当我null从 VueJS 应用程序为该字段传递一个值时,我都会得到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();
}

标签: c#asp.net-coreasp.net-core-3.1

解决方案


在@devNull 的建议之后,我发现在我玩 Rider IDE 时不知何故,它似​​乎打开了该功能!

骑手中有一个选项允许在项目级别更改该配置:

如果有人有同样的问题:右键单击项目级别,转到属性,应用程序,在那里你可以看到这个配置。

谢谢@devNull 的帮助:)

在此处输入图像描述


推荐阅读