2

Below is my request body for POST call to my web API.

  {
    "region" : "us-east-2",
    "namespaceName" : "com.xyx.demo.test",
    "tags": {
        "description": "Test Namespace",
        "purpose": "To store demo objects",
        ....
    }
  }

Here is the class that I am using to bind this request.

    public class Input
    {
        public string Region { get; set; }

        public string NamespaceName { get; set; }

        [Description("A set of key value pairs that define custom tags.")]
        public Dictionary<string, string> Tags { get; set; }
    }

I want to restrict my Tags Dictionary to create only 10 keys and each key's value should have not more than 256 characters.

So my ModelState should be invalid if more than 10 keys are provided or value contains more than 256 characters.

How can I do this using Data annotations ?

Code-47
  • 413
  • 5
  • 17
  • You can write custom validation annotation as given [here](https://stackoverflow.com/questions/16100300/asp-net-mvc-custom-validation-by-dataannotation) – Mahesh Oct 04 '18 at 06:18

2 Answers2

2

You create a custom validation attribute

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class YourAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (!(value is Dictionary<string, string>))
            return new ValidationResult("Object is not of proper type");

        var dictionary = (Dictionary<string, string>)value;

        if (dictionary.Count > 10)
            return new ValidationResult("Dictionary cant have more than 10 items");

        foreach (var keyValuePair in dictionary)
        {
            if (keyValuePair.Value.Length > 256)
                return new ValidationResult("Value cant be longer than 256.");
        }

        return ValidationResult.Success;
    }
}

Then your model

 public class Input
{
    public string Region { get; set; }

    public string NamespaceName { get; set; }

    [Description("A set of key value pairs that define custom tags.")]
    [YourAttribute]
    public Dictionary<string, string> Tags { get; set; }
}
XomRng
  • 171
  • 12
0

I do not think there is any existing utility available fro that. Only choice is to write your own converter like below

https://www.jerriepelser.com/blog/custom-converters-in-json-net-case-study-1/

ManishM
  • 583
  • 5
  • 7