当请求 Json 包含重复键时,我需要从 ASP.NET Web API Post 请求返回 400 错误。
例如,如果请求是
{
"key1": "value1",
"key2": 1000,
"key2": 2000,
"key3": "value3"
}
那么我希望由于有两个“key2”键而引发错误。
我的控制器方法看起来像
[HttpPost]
public IHttpActionResult PostMethod([FromBody]RequestModel request)
{
.....
}
和我的 RequestModel 模型一样
public class RequestModel
{
[Required]
public string Key1 {get; set; }
[Required]
public int Key2 {get; set; }
public string Key3 {get; set; }
}
在上面的示例中,Json 序列化程序似乎很乐意接受请求并使用 2000 或密钥的最后一个实例填充 Key2。
我想我需要做一些涉及 JsonSerializerSettings 类的事情,或者实现自定义 JsonConverter,但是我不确定如何继续。
这是一个自定义的 JsonConverter,它会抛出一个HttpResponseException
当遇到重复的键时,代码为 400,Asp.Net Web API 应自动处理它。
class DuplicateJsonConverter : JsonConverter
{
public override bool CanWrite { get { return false; } }
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var paths = new HashSet<string>();
existingValue = existingValue ?? Activator.CreateInstance(objectType, true);
var backup = new StringWriter();
using (var writer = new JsonTextWriter(backup))
do
{
writer.WriteToken(reader.TokenType, reader.Value);
if (reader.TokenType != JsonToken.PropertyName)
continue;
if (string.IsNullOrEmpty(reader.Path))
continue;
if (paths.Contains(reader.Path))
throw new HttpResponseException(HttpStatusCode.BadRequest); //as 400
paths.Add(reader.Path);
}
while (reader.Read());
JsonConvert.PopulateObject(backup.ToString(), existingValue);
return existingValue;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
你应该装饰你的RequestModel
使用此转换器的类。
[JsonConverter(typeof(DuplicateJsonConverter))]
class RequestModel
{
\\...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)