title: How to sanitize the value of string argument inside web api filter?
body: <p>I have web api  application and I want to sanitize data that comes from front-end applications using web api filters.</p>
  
  <p>I have created the following filter:</p>
  
  <pre><code>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 =&gt; x.CanRead &amp;&amp; x.PropertyType == typeof(string) &amp;&amp; x.GetGetMethod(true).IsPublic &amp;&amp; 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);
                  }
              }
          }
  
      }
  }
  </code></pre>
  
  <p>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:</p>
  
  <blockquote>
    <p>"ClassName": "System.InvalidOperationException",
            "Message": "Collection was modified; enumeration operation may not execute.</p>
  </blockquote>
  
  <p>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.</p>
  
  <p>So my question how to sanitize the passed argument in case it was string parameter?   </p>