0

Is there a way to get a dynamic object from query parameters in an ASP.NET Core WebAPI controller action?

When I try the following I get queries as an empty object

public object Action([FromQuery] dynamic queries)
{
    ...
}
2
  • How are you calling the endpoint? A similar question was asked here: stackoverflow.com/q/33018893/5803406 Commented Feb 9, 2020 at 22:26
  • Looks like a lord of the rings method (one method to rule them all). FWIW, Even if you could do this, you probably shouldn't. Commented Feb 9, 2020 at 22:27

1 Answer 1

0

Here is a workaround of customizing a model binder to bind the query string to Dictionary type:

DynamicModelBinder

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

        var result = new Dictionary<string, dynamic> { };
        var query = bindingContext.HttpContext.Request.Query;
        if (query == null)
        {
            bindingContext.ModelState.AddModelError("QueryString", "The data is null");
            return Task.CompletedTask;
        }

        foreach (var k in query.Keys)
        {
            StringValues v = string.Empty;
            var flag = query.TryGetValue(k, out v);
            if (flag)
            {
                if (v.Count > 1)
                {
                    result.Add(k, v);
                }
                else { 
                result.Add(k, v[0]);

                }
            }
        }

        bindingContext.Result = ModelBindingResult.Success(result);
        return Task.CompletedTask;
    }
}

Controller

public object Action([ModelBinder(BinderType = typeof(DynamicModelBinder))]dynamic queries)
    {
        return queries;
    }

Result enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.