Bruno
Bruno

Reputation: 418

Regroup WebAPI HttpGet methods parameters in one object

I have several HttpGet methods in my WebAPI controller, and most of them accept the same list of optional paramters. I was wondering if there would be a way to regroup them into one custom class object?

Example:

Replace

[HttpGet]
    public Object RunReport(int id, int? page = 1, int? pageSize = 50, String sortedBy = null, String sortDir = null, String eez = null, String species = null, int? groupBy = null, int? year = null, String flag = null, int? minYear = null, int? maxYear = null, String obsvPrg = null, int? setType = null, String setTypeCat = null, int? tripId = null){}

With

[HttpGet]
        public Object RunReport(int id, int? page = 1, int? pageSize = 50, QueryParams queryParams=null){}

using the following class

public class QueryParams
{
    public string SortedBy { get; set; }
    public string SortDir { get; set; }
    public string Eez { get; set; }
    public string Species { get; set; }
    public int? GroupBy { get; set; }
    public int? Year { get; set; }
    public string Flag { get; set; }
    public int? MinYear { get; set; }
    public int? MaxYear { get; set; }
    public string ObsvPrg { get; set; }
    public int? SetType { get; set; }
    public string SetTypeCat { get; set; }
    public int? TripId { get; set; }
    public string Gear { get; set; }
    public bool IsCount { get; set; }
}

Thanks for your help

Upvotes: 2

Views: 896

Answers (1)

Yishai Galatzer
Yishai Galatzer

Reputation: 8862

Yes that would work.

Depends on how you want to pass that object in, you can either

public object RunReport([FromUrl] QueryParams params)
{
     ...
}

use a Json/XML payload and then mark your method:

public object RunReport([FromBody] QueryParams params)
{
     ...
}

Or (that will work also for Form data + Query Data)

public object RunReport([ModelBinder] QueryParameter params)
{
   ...
}

Upvotes: 2

Related Questions