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