如何在Web Api发布请求Json中检测重复的密钥 [英] How to detect duplicate keys in Web Api Post request Json

查看:103
本文介绍了如何在Web Api发布请求Json中检测重复的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当请求Json包含重复的密钥时,我需要从ASP.NET Web API Post请求返回400错误.

I have a requirement to return a 400 error from an ASP.NET Web API Post request when the request Json contains duplicate keys.

例如,如果请求是

{
   "key1": "value1",
   "key2": 1000,
   "key2": 2000,
   "key3": "value3"
}

然后我希望由于有两个"key2"键而引发错误.

then I would want the error to be thrown due to there being two "key2" keys.

我的控制器方法看起来像

My controller method looks something like

[HttpPost]
public IHttpActionResult PostMethod([FromBody]RequestModel request)
{
   .....
}

和我的RequestModel模型

and my RequestModel model like

public class RequestModel
{
    [Required]
    public string Key1 {get; set; }

    [Required]
    public int Key2 {get; set; }

    public string Key3 {get; set; } 
}

在上面的示例中,Json序列化程序似乎很高兴接受请求并用2000或其他密钥的最后一个实例填充Key2.

In the example above the Json serializer seems happy to accept the request and populate Key2 with 2000, or whatever the last instance of the key is.

我想我需要做一些涉及JsonSerializerSettings类的事情,或者实现一个自定义的JsonConverter,但是我不确定如何进行.

I am thinking I need to do something involving the JsonSerializerSettings class, or implement a custom JsonConverter, however I am unsure how to proceed.

推荐答案

这是一个自定义JsonConverter,当遇到Asp.Net Web API应该自动处理的重复密钥时,它会抛出带有代码400的HttpResponseException. >

Here is a custom JsonConverter which throws an HttpResponseException with code 400 when encounters to a duplicated key which Asp.Net Web API should automatically handle it.

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类.

and you should decorate your RequestModel class using this converter.

[JsonConverter(typeof(DuplicateJsonConverter))]
class RequestModel
{
  \\...
}

这篇关于如何在Web Api发布请求Json中检测重复的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆