1

Hi I have the following route in my web api:

[Route("Resource/")]
[HttpGet]
public IActionResult Get([FromQuery] IEnumerable<string> filterItems = null)
{
}

In .Net Framework 4.8, whenever I would call this without specifying any filterItems it would default the IEnumerable to null which is the behaviour I'm looking for. After migrating to .Net Core 3.1, I now get an empty list instead.

Anyone know how I can default the nullable list to null (= null works with any other type, but lists seem problematic)?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

0

You can try to use a custom model binding.Here is a demo: Action:

[Route("Resource/")]
[HttpGet]
public IActionResult Get([ModelBinder(typeof(CustomBinder))]IEnumerable<string> filterItems)
{
}

CustomBinder:

public class CustomBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }
            List<string> model=new List<string>();
            var l = bindingContext.ValueProvider.GetValue("filterItems[0]").FirstValue;

            if (l != null)
            {
                int i = 0;
                while (bindingContext.ValueProvider.GetValue("filterItems[" + i + "]").FirstValue != null)
                {
                    model.Add(bindingContext.ValueProvider.GetValue("filterItems[" + i + "]").FirstValue);
                    i++;
                }
                bindingContext.Result = ModelBindingResult.Success(model);
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Success(null);
            }
            
            return Task.CompletedTask;
        }
    }

result: enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • Okay, I get this. But does this remove the ability to specify an empty list? What I would like is the ability to pass a "null" list, as well as any empty list. How might that be done? – Alex Dresko Oct 19 '21 at 15:14
  • @AlexDresko is correct; this moves the problem to now not being able to have empty lists if defined empty. – UnLuckyNiko Nov 04 '22 at 16:22
  • @UnLuckyNiko I looked into this again recently and couldn't find a good solution. To me, what makes the most sense, is that all lists are non-null and empty by default. You can pass a list of items the normal way: ?filterItems=something&filterItems=another&...`. But if you want a null list, you should be able to say `?filterItems=null`. `null` becomes the single magic string that allows a list to be null. OR, lists are null by default, and you could `?filterItems=empty` if you want an empty, non-null list. I've just never taken time to do it. – Alex Dresko Nov 04 '22 at 20:22