C# Json验证:为属性强制执行一组特定的值

C# Json验证:为属性强制执行一组特定的值,c#,.net,json.net,C#,.net,Json.net,我在上配置了一个API项目以使用: Startup.cs public void配置服务(IServiceCollection服务) { // [...] services.AddControllers().AddNewtonsoftJson(); // [...] } Data.cs 使用系统; 使用System.Collections.Generic; 使用Newtonsoft.Json; 名称空间MyNS { [JsonObject] 公共类MyData { [JsonProperty(

我在上配置了一个API项目以使用:

Startup.cs

public void配置服务(IServiceCollection服务)
{
// [...]
services.AddControllers().AddNewtonsoftJson();
// [...]
}
Data.cs

使用系统;
使用System.Collections.Generic;
使用Newtonsoft.Json;
名称空间MyNS
{
[JsonObject]
公共类MyData
{
[JsonProperty(“查询”,Required=Required.Always)]
公共查询查询{get;set;}
[JsonProperty(“限额”)]
公共整数限制{get;set;}
}
公共类查询
{
[JsonProperty(“props”,Required=Required.Always)]
公共列表道具{get;set;}
}
公共类道具
{
//允许的值应仅为(“key1”和“key2”)。其他字符串或类型的验证应失败
[JsonProperty(“key”,Required=Required.Always)]
公共字符串密钥{get;set;}
[JsonProperty(“value”,Required=Required.Always)]
公共字符串值{get;set;}
}
}
MyController.cs

/[…]
[路线(“测试”)]
[HttpPost]
公共异步任务测试(MyData)
{
返回Json(数据);
}
// [...]

对于特定属性(本例中为Prop.Key),如果该值与特定设置值(例如“key1”和“key2”)不同,我需要验证失败。有没有可能在
Newtonsoft.Json
中配置这样的验证?

正如建议的那样,似乎使用
enum
而不是
string
可以解决问题

不要使用字符串,而是使用
enum
。您可以查看
IValidatableObject
接口