Last active
November 22, 2017 21:37
-
-
Save arielmoraes/63a39a758026b47483c405b77c3e96b9 to your computer and use it in GitHub Desktop.
Validate null complex type models when query string is empty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ActionFilter : ActionFilterAttribute, IFilter | |
{ | |
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) | |
{ | |
actionContext.ValidateNullModel(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[HttpGet] | |
[Route("")] | |
public IHttpActionResult Get([FromUri][NotNull] ComplexType request) | |
{ | |
return Ok(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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