Skip to content

Instantly share code, notes, and snippets.

@testfirstcoder
Last active March 22, 2016 10:54
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 testfirstcoder/b3a6fa1908980d50da87 to your computer and use it in GitHub Desktop.
Save testfirstcoder/b3a6fa1908980d50da87 to your computer and use it in GitHub Desktop.
ActionFilterAttribute for model validation
public class ModelValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var arguments = actionContext.ActionArguments;
var request = actionContext.Request;
if (HasNullArgument(arguments))
{
string message = $"{arguments.First(_ => _.Value == null).Key} cannot be null.";
actionContext.Response = request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
}
else if (!actionContext.ModelState.IsValid)
{
actionContext.Response = request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
private static bool HasNullArgument(Dictionary<string, object> arguments) => arguments.Any(_ => _.Value == null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment