Skip to content

Instantly share code, notes, and snippets.

@arielmoraes
Last active November 22, 2017 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arielmoraes/63a39a758026b47483c405b77c3e96b9 to your computer and use it in GitHub Desktop.
Save arielmoraes/63a39a758026b47483c405b77c3e96b9 to your computer and use it in GitHub Desktop.
Validate null complex type models when query string is empty
public static class ActionContextExtensions
{
public static void ValidateNullModel(this HttpActionContext actionContext)
{
var notNullParametersDescriptors = actionContext.ActionDescriptor.GetParameters()
.Where(p => p.GetCustomAttributes<NotNullAttribute>().Count > 0);
foreach (var pd in notNullParametersDescriptors)
{
var model = actionContext.ActionArguments[pd.ParameterName];
if (model == null)
{
model = Activator.CreateInstance(pd.ParameterType);
actionContext.ActionArguments[pd.ParameterName] = model;
}
}
}
}
public class ActionFilter : ActionFilterAttribute, IFilter
{
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
actionContext.ValidateNullModel();
}
}
[HttpGet]
[Route("")]
public IHttpActionResult Get([FromUri][NotNull] ComplexType request)
{
return Ok();
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public class NotNullAttribute : Attribute
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment