在ASP.NET Core WebApi控制器中,我尝试返回json { payload: myArray }
[HttpGet]
public async Task<IActionResult> GetEntriesPaged(int? page, int pageSize = 10) {
...
return Ok( await new { payload = query.ToListAsync() }); }
错误CS1061'有效负载>'不包含 “ GetAwaiter”的定义,没有可访问的扩展方法 可以找到'GetAwaiter'接受类型为'payload>'的第一个参数(您是否缺少 指令还是程序集引用?)
PS。整个功能让大家更好地了解
[HttpGet]
public async Task<IActionResult> GetEntriesPaged(int? sourceId, string filter, int? pageIndex, int pageSize = DEFAULT_PAGESIZE, string sortOrder = Order.DESC) {
IQueryable<Entry> query = _db.Entries;
// 0. Filter by sourceId
if (sourceId.HasValue) {
query = query.Where(e => e.SourceId == sourceId.Value);
}
// 1. Filter by message or subject or from or to
if (!string.IsNullOrWhiteSpace(filter)) {
query = query.Where(e => e.Message.Contains(filter) || e.Subject.Contains(filter) || e.From.Contains(filter) || e.To.Contains(filter));
}
// 2. Order by Date
if (string.IsNullOrWhiteSpace(sortOrder) || sortOrder.ToLower() != Order.ASC) { sortOrder = Order.DESC; }
sortOrder = sortOrder.ToLower();
if (sortOrder == Order.ASC) {
query = query.OrderBy(x => x.Date);
}
else {
query = query.OrderByDescending(x => x.Date);
}
// 3. Get paged elements (Skip & Take)
if (pageIndex.HasValue) {
if (pageIndex < 0) { pageIndex = 0; }
if (pageSize < 1) { pageSize = 1; }
int take = pageSize;
int skip = (pageIndex.Value * pageSize);
var paginationMetadata = new {
totalCount = query.Count(),
pageSize = pageSize,
currentPage = pageIndex
};
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata));
query = query.Skip(skip).Take(take);
}
return Ok( await new { payload = query.ToListAsync() });
}
答案 0 :(得分:2)
您需要等待ToListAsync
:
return Ok( new { payload = await query.ToListAsync() });