在一个对象中重新组合WebAPI HttpGet方法参数

时间:2014-04-29 04:38:39

标签: c# asp.net-web-api

我的WebAPI控制器中有几个HttpGet方法,并且大多数方法都接受相同的可选参数列表。我想知道是否有办法将它们重新组合成一个自定义类对象?

示例:

替换

[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){}

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

使用以下课程

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; }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

是的,这样可行。

取决于您希望如何传递该对象,您可以

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

使用Json / XML有效负载,然后标记您的方法:

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

或(也适用于表单数据+查询数据)

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