Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding ActionFilterAttribute Checking For Null

Tags:

c#

asp.net

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);
        }
    }
}
like image 250
user1848850 Avatar asked Nov 21 '25 00:11

user1848850


1 Answers

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

like image 50
user1848850 Avatar answered Nov 23 '25 14:11

user1848850



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!