How to detect duplicate keys in Web Api Submit a Json request

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

For example, if the request was

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

then I would like the error to be selected due to the presence of two "key2" keys.

My controller method looks something like

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

and my RequestModel model for example

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

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

    public string Key3 {get; set; } 
}

In the above example, the Json serializer seems to be happy to accept the request and populate Key2 with 2000 or any other last key instance.

I think I need to do something with the JsonSerializerSettings class or implement a custom JsonConverter, however I'm not sure how to do this.

+4
2

JsonConverter, HttpResponseException 400 , Web-API Asp.Net.

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
{
  \\...
}
+1

DelegateHandler, , . , , . :

GlobalConfiguration.Configuration.MessageHandlers.Add(new YourDelegateHandler());
+1

All Articles