Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change input parameters using Action Filters

The background:

I am trying to fix a potential security issue to remove single quotes injected in as string parameters to my WebAPI method (this needs to be done throughout the application).

I tried to accomplish this by creating an Action Filter which does the necessary

public class ValidateActionParametersAttribute : ActionFilterAttribute, IActionFilter
    {
        public override void OnActionExecuting(HttpActionContext actionExecutedContext)
        {          
            var parameters = actionExecutedContext.ActionArguments;
            var parameterList = parameters.Values.ToList();
            parameterList.Where(x => x.GetType() == typeof(string)).ToList().ForEach(y => y = y.ToString().Replace("\'", ""));            
            base.OnActionExecuting(actionExecutedContext);
        }
    }

And registered it globally in my WebApiConfig

config.Filters.Add(new ValidateActionParametersAttribute());

But when I checked after placing a breakpoint in the code the parameter changes done in the ActionFilter does not seem to reflect. Can someone guide me what I am doing wrong?

like image 450
Suraj Nair Avatar asked Oct 14 '25 14:10

Suraj Nair


1 Answers

You are not updating the value in the arguments dictionary but you are only replacing the y parameter of the lambda function you pass to ForEach.

Since ActionArguments is a dictionary you can do the follwing:

var stringArgs = context.ActionArguments.Where(pair => pair.Value is string).ToList();

foreach (var keyValue in stringArgs)
{
    var safeValue = ((string)keyValue.Value).Replace("\'", "");
    context.ActionArguments[keyValue.Key] = safeValue;
}

This will get all arguments which are strings and replace them with the safe version.

like image 80
DB. Avatar answered Oct 17 '25 05:10

DB.



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!