Last active
March 22, 2016 10:54
-
-
Save testfirstcoder/b3a6fa1908980d50da87 to your computer and use it in GitHub Desktop.
ActionFilterAttribute for model validation
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 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