September 8, 2016 by Christoff Truter ASP.NET Web API
The ModelState.IsValid property (ApiController) merely checks for a zero validation error count for a passed model while ignoring the nullability of the object instance itself.
Which basically means that a null model will always be valid regardless of its data annotations, which seems a bit ill-defined don't you think?
An obvious solution is to simply do a null check on the model, a more elegant solution is to make use of action filters, allowing us to perform certain actions before or after an action is invoked.
Have a look at the following piece of code.
public class NullModelStateActionFilter : ActionFilterAttribute
{
public bool ReturnsBadRequest { get; set; } = false;
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ActionDescriptor.GetCustomAttributes<NullableModelAttribute>().Any() && actionContext.ActionArguments.ContainsValue(null))
{
actionContext.ModelState.AddModelError("Error", "Null Model Not Allowed");
if (ReturnsBadRequest)
{
actionContext.Response = actionContext.Request.CreateErrorResponse
(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
}
The action filter defined in the preceding snippet basically firstly checks for the presence of the NullableModelAttribute (as defined in the snippet below).
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class NullableModelAttribute : Attribute { }
GlobalConfiguration.Configuration.Filters.Add(
new NullModelStateActionFilter
{
ReturnsBadRequest = true
}
);