0

Actually on my .NET Core project i'm using a simple modelbinder to trim input string

public class StringModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != ValueProviderResult.None)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            string valueAsString = string.IsNullOrWhiteSpace(valueAsString) ? null : valueAsString.Trim();

            bindingContext.Result = ModelBindingResult.Success(valueAsString);
        }

        return Task.CompletedTask;
    }
}

I use it through the IModelBinderProvider and it works perfectly on input of type string. However I notice that it's not fired when on input I have a collection of string like this

public IActionResult CollectionTrimTest([FromBody] List<string> values)

To perform it I think I should use something like

if (context.Metadata.IsCollectionType)
    return new BinderTypeModelBinder(typeof(CollectionModelBinder));

but I really don't know how to implement CollectionModelBinder to trim result based on string collection. Centralizing the trim logic between StringModelBinder and CollectionModelBinder would be greatly appreciated of course.

Sauron
  • 2,156
  • 5
  • 17
  • 20

1 Answers1

0

Solved, seems [FromBody] must require a JsonConverter. More information at https://stackoverflow.com/a/54663595/4963176

Sauron
  • 2,156
  • 5
  • 17
  • 20