C# 将属性标记为Newtonsoft所需的Json只会使对象为空
我的API有一个请求对象,我想强制执行我的属性始终存在于主体中。这是我的目标:C# 将属性标记为Newtonsoft所需的Json只会使对象为空,c#,json.net,C#,Json.net,我的API有一个请求对象,我想强制执行我的属性始终存在于主体中。这是我的目标: public class Code { [JsonProperty("id", Required = Required.Always)] public string id { get; set; } [JsonProperty("type", Required = Required.Always)] public string type { g
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装饰师不会在这里为我做这些吗?或者我必须手动添加检查以查看属性是否为空?是您的解决方案。因此,您不必使用JsonProperty
属性
用法:
首先,为类创建一个验证器
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.
}
...
}
所以,当你得到所有的错误。现在您可以随心所欲地展示。
当前,JsonProperty.Required的值仅确定该值是否为必需值-它不允许您指示值是否为null
此外,在查看代码时,看起来所有空字符串都被转换为null
以下代码按预期为我抛出:
string serialized=@“{'noId':'123'}”;
Code deserialized=JsonConvert.DeserializeObject(序列化);
Console.WriteLine(反序列化的.Id);
我的代码类:
类代码
{
[JsonProperty(“id”,Required=Required.Always)]
公共字符串Id{get;set;}
}
你能确认使用了Newtonsoft.Json吗?如果您使用的是ASP.NET Core 3.x或更高版本,请参阅将您的项目设置为使用
Newtonsoft.Json
请共享。。。首先,您没有使用json.net(因为新的asp.net核心不再使用json.net,而是使用System.Text,json),但这只是盲目猜测。Newtonsoft没有用作默认序列化程序,这似乎是一个问题