Home > Mobile >  Best way to preprocess controller input values
Best way to preprocess controller input values

Time:12-12

I have a Web API controller with some input values, for instance:

[HttpGet]
public IList<string> Search(string pattern) {
    
}  

I would like to preprocess input value and replace all symbols '*' with '%'. Let my clients send me value like 'Jo*' but I want to see 'Jo%' inside controller method. I would like to have a special attribute for that. Something like

Search ([ProcessForSql] string pattern) {...}

Is it possible? Or maybe there is some more appropriate way to implement preprocessing for input values?

CodePudding user response:

You can create a custom model binding to achieve it.

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

            

            var modelName = bindingContext.ModelName;

            var values = bindingContext.ValueProvider.GetValue(modelName);
            if (values.Length == 0)
                return Task.CompletedTask;

            var result = values.FirstValue?.Contains("*");
            if ((bool)result)
            {
                var a = values.FirstValue?.Replace("*","%");
                bindingContext.Result = ModelBindingResult.Success(a);
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Success(values.ToString());
            }

            return Task.CompletedTask;
        }
    }

Then use this custom modelbinder in your action:

[HttpGet]
public IList<string> Search([ModelBinder(BinderType = typeof(MyModelBinder))] string pattern) {
    
}  

Demo:

enter image description here

  • Related