【问题标题】:The string field is required. even thou there is no Required attribute in Asp.Net Core?字符串字段是必需的。即使您在 Asp.Net Core 中也没有必需的属性?
【发布时间】: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


【解决方案1】:

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

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

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

感谢@devNull 的帮助:)

【讨论】:

    【解决方案2】:

    我看到了同样的问题,即 .csproj Nullable 设置导致未标记为 [Required] 的属性表现得好像是一样。我采用了与更改 .csproj 文件中的 Nullable 设置不同的方法。

    就我而言,它归结为数据库所需的属性;但是该模型在 POST 期间允许为 null,因为此特定属性是用户的秘密。所以我最初避免将string 更改为string?

    Fluent API 再次提供了替代解决方案。

    原始属性

    [JsonIgnore]
    [StringLength(15)]
    public string MyProperty { get; set; }
    

    更新的属性

    [JsonIgnore]
    public string? MyProperty { get; set; }
    

    Fluent API 指令(在您的 DbContext 文件中)

    protected override void OnModelCreating(ModelBuilder builder) {
      builder.Entity<MyClass>(c => {
        c.Property(p => p.MyProperty)
          .IsRequired()
          .HasMaxLength(15)
          .IsFixedLength();
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多