How to sanitize the value of string argument inside web api filter?

Viewed 1446

I have web api application and I want to sanitize data that comes from front-end applications using web api filters.

I have created the following filter:

public class StringFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        foreach (var actionArgument in actionContext.ActionArguments)
        {
            if (actionArgument.Value.GetType() == typeof(string))
            {
                var sanitizedString = actionArgument.Value.ToString().Trim();
                sanitizedString = Regex.Replace(sanitizedString, @"\s+", " ");
                actionContext.ActionArguments[actionArgument.Key] = sanitizedString;
            }
            else
            {
                var properties = actionArgument.Value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                    .Where(x => x.CanRead && x.PropertyType == typeof(string) && x.GetGetMethod(true).IsPublic && x.GetSetMethod(true).IsPublic);
                foreach (var propertyInfo in properties)
                {
                    var sanitizedString = propertyInfo.GetValue(actionArgument.Value).ToString().Trim();
                    sanitizedString = Regex.Replace(sanitizedString, @"\s+", " ");
                    propertyInfo.SetValue(actionArgument.Value, sanitizedString);
                }
            }
        }

    }
}

The problem with this code is the code inside if statement where I want to sanitize the arguments passed as single string I got this error:

"ClassName": "System.InvalidOperationException", "Message": "Collection was modified; enumeration operation may not execute.

But if my web api action takes a parameter as dto object which has string properties the code(which is inside the else statement) is working perfectly and strings are sanitized before starting executing the action.

So my question how to sanitize the passed argument in case it was string parameter?

1 Answers
Related