Search code examples
c#asp.net-web-apidata-annotationsform-datasystem.componentmodel

Validating Form Data For null values in web api


I have class like

public class MyClass
{
  public object Jobj{get; set;}
  public string summary{get; set;}

 public string someMethod()
 {
  //Do some work
  return "";
 }
}

and a post action creating instance of this class and initialising properties with form data inputs

        [HttpPost]
        public dynamic controllerAction()
        {
            try
            {
                var instance= new MyClass
                {
                    Jobj= JObject.Parse(HttpContext.Current.Request.Params["formInputKey1"]),
                    summary= HttpContext.Current.Request.Params["summaryKey"]
                };
                return instance.SomeMethod();
            }
            catch (Exception ex)
            {
                return ex;
            }
        }

I wanted to know how to enforce null property check for form-data input

What I tried:

public class MyClass
{
  [Required]
  public object Jobj{get; set;}
  [Required(AllowEmptyStrings = false), StringLength(maximumLength: 100, MinimumLength = 1)]
  public string summary{get; set;}

 public string someMethod()
 {
  //Do some work
  return "";
 }
}

and a post action creating instance of this class and initialising properties with form data inputs

        [HttpPost]
        public dynamic controllerAction()
        {
            try
            {
                var instance= new MyClass
                {
                    Jobj= JObject.Parse(HttpContext.Current.Request.Params["formInputKey1"]),
                    summary= HttpContext.Current.Request.Params["summaryKey"]
                };
                var isModelStateValid = ModelState.IsValid;
                if(!isModelStateValid )
                {
                   throw ArgumentException("Found Data Null");
                }
                return instance.SomeMethod();
            }
            catch (Exception ex)
            {
                return ex;
            }
        }

But ModelState.IsValid is always true as it was containing count = 0


Solution

  • In order to use ModelState.IsValid, if speaking simply, you should use the object as parameter to the method

    public dynamic controllerAction(MyClass x)
    

    ModelState.IsValid, again, if put simply, is populated by ModelBinder (basically a thing that "serializes" your Action arguments), not just by JObject.parse or anything like that.

    Then if you cannot use default ModelBinder you can write your own - https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-5.0 (this link is for .NET 5, but basically the same thing and idea is valid for old MVC/WebApi as well)

    Alternatively if you still want to use your code, you can simply trigger default validation using Validator class: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validator?view=net-5.0

    It throws the exception if object is not valid according to attributes you defined.