i'm trying to understand this ActionFilterAttribute. I've tried to play around with the code a bit to get a better understanding of how it works but i'm completely lost.
Here's the working ActionFilterAttribute. It is supposed to check for a null request body and return an error:
public class CheckModelForNullAttribute : ActionFilterAttribute
{
private readonly Func<Dictionary<string, object>, bool> _validate;
public CheckModelForNullAttribute() : this(arguments => arguments.ContainsValue(null))
{ }
public CheckModelForNullAttribute(Func<Dictionary<string, object>, bool> checkCondition)
{
_validate = checkCondition;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (_validate(actionContext.ActionArguments))
{
var modelState = new ModelStateDictionary();
modelState.AddModelError("Parameter", "The request body cannot be null");
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
Why doesn't this produce the same results:
public class CheckModelForNullAttribute: ActionFilterAttribute
{
private readonly Func<Dictionary<string, object>, bool> _validate = args => args.ContainsValue(null);
public override void OnActionExecuting(HttpActionContext filterContext)
{
if (!_validate(filterContext.ActionArguments))
{
filterContext.ModelState.AddModelError("Parameter", "The request body cannot be null");
filterContext.Response = filterContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, filterContext.ModelState);
}
}
}
Dumb mistake on my part:
if (_validate(actionContext.ActionArguments))
in the first class
if (!_validate(filterContext.ActionArguments))
in the second class.
The solution, remove the ! and it works the same.
Thank you haim770 for hinting at that! Guess i was tired and could not see that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With