如何使控制器具有变化的参数?

时间:2018-12-20 12:16:50

标签: c# asp.net-core asp.net-core-webapi

我有这样的要求:

GET: /accounts/filter/?status_neq=test&birth_lt=643972596&country_eq=Endgland&limit=5&query_id=110

因此,下一个请求代码如下:

GET: /accounts/filter/?status_eq=test&birth_gt=643972596&country_year=1970&limit=5&query_id=110

以此类推。

我创建了简单的控制器,但我不知道如何执行此操作,因此您无法在控制器中接受此类可变输入参数:

[ResponseCache(CacheProfileName = "FilterCache", Duration = 10, Location = ResponseCacheLocation.Any, NoStore = false)]
[Route("/accounts/filter/")]
[ApiController]
public class FilterController : ControllerBase
{
    // GET: api/Filter
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET: api/Filter/5
    [HttpGet("{id}", Name = "Get")]
    public string Get(int id)
    {
        return "value";
    }

    // POST: api/Filter
    [HttpPost]
    public void Post([FromBody] string value)
    {
    }

    // PUT: api/Filter/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
    }

    // DELETE: api/ApiWithActions/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

2 个答案:

答案 0 :(得分:2)

您需要将其作为参数列表传递到控制器内部的操作方法,也可以使用FromQuery属性。

[ResponseCache(CacheProfileName = "FilterCache", Duration = 10, Location = ResponseCacheLocation.Any, NoStore = false)]
[Route("/accounts/filter/")]
[ApiController]
public class FilterController : ControllerBase
{
    // GET: /accounts/filter/?status_eq=test&birth_gt=643972596&country_year=1970&limit=5&query_id=110
    [HttpGet]
    public IEnumerable<string> Get(string status_eq, long birth_gt, int country_year, int limit, int query_id)
)
    {
        return new string[] { "value1", "value2" };
    }
}

[ResponseCache(CacheProfileName = "FilterCache", Duration = 10, Location = ResponseCacheLocation.Any, NoStore = false)]
[Route("/accounts/filter/")]
[ApiController]
public class FilterController : ControllerBase
{
    // GET: /accounts/filter/?status_eq=test&birth_gt=643972596&country_year=1970&limit=5&query_id=110
    [HttpGet]
    public IEnumerable<string> Get([FromQuery] string status_eq, [FromQuery] long birth_gt, [FromQuery] int country_year, [FromQuery] int limit, [FromQuery] int query_id)
)
    {
        return new string[] { "value1", "value2" };
    }
}

答案 1 :(得分:1)

通常,您应该为不同的查询字符串定义不同的参数。

如果您不想在控制器操作中指定参数,则可以尝试HttpContext.Request.Query获取所有查询字符串。

public ActionResult MultipleParameters()
{
    var parameters = HttpContext.Request.Query;
    return Ok(parameters.ToList());
}