首页 > 解决方案 > 在 IQueryable 上返回 204 状态代码Web API 操作

问题描述

web api我正在使用toJSONcustom CVS解析器导出大量数据。一切正常,但我想204 status code在查询返回 0 条记录时返回。我没有找到一种方法来设置状态码,因为我IQueryable<Log>在行动中返回。有什么建议吗?

   [HttpGet]
   [Route("user/statistic")]

    public IQueryable<Log> Statistic(int userId, DateTime startDate, DateTime endDate, CancellationToken cancellationToken)
    {

        var logs = _context.Find(userId, startDate, endDate);
        return logs;
    }

    public IQueryable<Log> Find(int userId, DateTime startDate, DateTime endDate)
    {
        var startDateSql = startDate.AddDays(-1).Date;
        var endDateTimeSql = endDate.AddDays(1).Date;
        return Logs.Where(w => w.UserId == userId && w.DateStamp > startDateSql && w.DateStamp < endDateTimeSql).AsNoTracking();
    }

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

解决方案


尝试使用IActionResult而不是IQueryable你的 API 方法,那么你可以有这样的东西:

public IActionResult MyApi()
{
    // if the result has any item
    return Ok(result);

    // otherwise
    return NoContent(); // which returns 204 status code
}

推荐阅读