How to detect duplicate keys in Web Api Post request Json

混江龙づ霸主 提交于 2019-12-05 16:58:17

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();
    }
}

and you should decorate your RequestModel class using this converter.

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

You can create an intercepting DelegateHandler which will fire every time you get a request. In it you can get the data which is sent to your controller and check if it has duplicate keys. Created handler is registered like this:

GlobalConfiguration.Configuration.MessageHandlers.Add(new YourDelegateHandler());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!