How to pass an Object as a query parameter in Get API request ASP.NET Core

By reading this title some beginners and new to programming peeps will be amazed that how can we pass a JSON object as a query parameter in “Get” type API using ASP.NET Core.

In this post, we will discuss and learn that how can we perform this task in our ASP.NET Core Web API project. It is very simple and easy.

Tools:

Visual Studio Community 2019

Windows OS

Let’s get started:

We will perform this task in the ASP.NET Core Web API project. If you want to create ASP.NET Core N-tier Application you can set it up by following this LINK.

First of all, we have to create a Model that we are going to receive in the “GET” API as an object. Let’s create a class we are going to name it “FilterViewModel.cs”

public class FilterViewModel
    {
        public int PageNo { get; set; }
        public int PageSize { get; set; }
        public string Query { get; set; }
        public string SortBy { get; set; }
        public bool? SortDesc { get; set; }
        public bool? Status { get; set; }
    }

This is the object that we will receive as a query parameter in our API.

Now we will create two classes that will be extended by “IModelBinderProvider”.

public class FilterModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var jsonString = bindingContext.ActionContext.HttpContext.Request.Query["Filter"];
            FilterViewModel result = JsonConvert.DeserializeObject<FilterViewModel>(jsonString);

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

    public class FilterModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context.Metadata.ModelType == typeof(FilterViewModel))
                return new FilterModelBinder();

            return null;
        }
    } 

This “FilterModelBinderProvider” class will check the query parameter and if it’s “FilterViewModel.cs” type it will return a response “new FilterModelBinder()” and in this ”FilterModelBinder” class we have implemented a method that will deserialize the JSON Object in our “FilterViewModel”. Please note that we clearly mentioned the name of our object while we are binding query requests.

bindingContext.ActionContext.HttpContext.Request.Query["Filter"];

Please make sure that the object you are sending in the query parameter does have the same name as you have described over here.

Now we have implemented our logic in this class. We also have to configure this “ModelBinderProvider” in our “Startup.cs” class.

services.AddControllers(options => {
                options.ModelBinderProviders.Insert(0, new FilterModelBinderProvider());
                options.Filters.Add(typeof(Authorization));
            }).AddNewtonsoftJson(opts =>
            {
                opts.SerializerSettings.ContractResolver = new DefaultContractResolver();
                opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            }).AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null);
}

Here we have configured our “ModelBinderProvider”. Now if any of our GET API requests will ever have an object with the name of “filter” It will be deserialized in the “FilterViewModel” type.

Note: You can not call this API from swagger this API will only be called by your front-end frameworks like VueJS, ReactJS, Angular, or Postman.

Your API will look like this.

Object as a query parameter

Conclusion:

Try this tutorial and if you do not understand anything or face any issue while applying this method. Do not hesitate to comment below. Team MYCODEBIT will try to respond ASAP.

Leave a Reply

Your email address will not be published.