ASP.NET Core 6 Web API - 使字段成为必填项

Ane*_*eef 24 asp.net-web-api asp.net-core .net-6.0 visual-studio-2022

我有一个基本的 CRUD API,它将模型保存到运行良好的 MongoDB 中。

该模型如下所示:

[BsonIgnoreExtraElements]
public class Configuration
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [Display(Name = "Parameter Name")]
    [Required]
    public string ParamName { get; set; }
    [Display(Name = "Parameter Value")]
    [Required]
    public string ParamValue { get; set; }
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的动作看起来像这样:

[HttpPost(Name = "Create")]
[Produces("application/json")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<ApiResult>> Create(Configuration configuration)
{
        try
        {
            var res = await _configurationRepository.Add(configuration);
            // DO OTHER STUFF
        }
        catch (Exception ex)
        {
            //error handling stuff
        }
}
Run Code Online (Sandbox Code Playgroud)

当我将此代码移植到 .NET 6 时,我通过 Postman 尝试上述操作,但收到此错误:

"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "发生一个或多个验证错误。",
"status": 400,
"Id 字段是必须的。”

知道为什么会发生这种情况吗?字符串字段也会发生同样的情况。这只是一个例子,基本上我的大部分操作都因这一更改而不起作用。

Ane*_*eef 29

这是由于 ASP.Net 6 中的一些模型验证更改(不可空引用类型)

能够通过执行以下操作解决此问题:

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

services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
Run Code Online (Sandbox Code Playgroud)

  • 我认为它只适用于隐式必需的属性。不明确 (3认同)

小智 18

2种可能的解决方法:

解决方法1

builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
Run Code Online (Sandbox Code Playgroud)

解决方法2

或者将所有字符串类型更改为字符串?来自配置类。

额外说明

另外 -AddControllersWithViews()可以使用相同的选项设置来调用。例如:

builder.Services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
Run Code Online (Sandbox Code Playgroud)

  • 字符串?指的是 dot net 6 为已经隐式可为 null 的事物引入了显式可为 null 性。他的答案是通过在类型后加上问号来使字符串显式可为空。因此可为空字符串。据我看来,他的回答没有任何问题。 (2认同)

Jal*_*eel 12

有 3 个选项可以解决此问题。您可以尝试其中任何一种来使其工作:

  1. 检查您的 csproj 文件是否包含条目<Nullable>enable</Nullable>. 如果是,请将其删除。

  2. 改成public string Id { get; set; }public string? Id { get; set; }

3.将此行添加到Program.cs中

builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
Run Code Online (Sandbox Code Playgroud)

- 干杯