使用 Newtonsoft 将 属性 标记为 Json Required 只会使对象为 null

Marking a property as Json Required with Newtonsoft just makes object null

我的 API 有一个请求对象,我想强制我的属性始终存在于正文中。这是我的对象:

public class Code
{
    [JsonProperty("id", Required = Required.Always)]
    public string id { get; set; }

    [JsonProperty("type", Required = Required.Always)]
    public string type { get; set; }
}

然而,当我没有在请求正文中传入 type 属性 时,我的 Code 对象为空。相反,我希望将错误的请求错误传播回客户端。 Newtonsoft 装饰器不会在这里为我做那个吗?或者我是否必须手动添加检查以查看属性是否不为空?

Fluent Validation 是适合您的解决方案。因此,您不必使用 JsonProperty 属性。

用法:

首先,为您的 class 创建一个验证器。

public class CodelValidator : AbstractValidator<Code>
{
    public CodelValidator()
    {
        RuleFor(x => x.id).NotEmpty().WithMessage("id is required.");
        RuleFor(x => x.type).NotEmpty().WithMessage("type is required.");
    }
}

在你的控制器方法中:

public ActionResult TestMethod(Code code)
{
    var validator = new CodeValidator();
    var validationResult = await validator.ValidateAsync(code);
    if (validationResult.IsValid == false)
    {
        var errorMessages = validationResult.Errors.Select(s => s.ErrorMessage);
        // manage how you want to show the erros.
    }
    ...
}

因此,当您遇到所有错误时。现在你可以随心所欲地展示了。

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1064

目前 JsonProperty.Required 的值仅确定是否需要该值 - 它不允许您指示值可以为 null 也可以不为 null。

另外,在查看代码时,似乎所有空字符串都被转换为 null

https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs#L282

以下代码按预期为我抛出:

string serialized = @"{ 'noId': '123' }";  
Code deserialized = JsonConvert.DeserializeObject<Code>(serialized);
Console.WriteLine(deserialized.Id);

我的代码class:

    class Code
    {
        [JsonProperty("id", Required = Required.Always)]
        public string Id { get; set; }
    }

您能确认使用了 Newtonsoft.Json 吗?如果您使用 ASP.NET Core 3.x 或更高版本,请参考 设置您的项目以使用 Newtonsoft.Json.