【问题标题】:Adding Sort, Pagination and filtering to ASP.NET Api向 ASP.NET Api 添加排序、分页和过滤
【发布时间】:2021-02-28 12:07:16
【问题描述】:

你能告诉我如何在我的 ASP.NET Web API 中添加排序、过滤和分页,所以我可以这样写 url

http://localhost:8000/api/Meetings?sort_by=name&sort_type=asc&s=Joh&page=1&page_size=3

我有这个MeetingsController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
    [Route("api/Meetings")]
    [ApiController]
    public class MeetingsController : ControllerBase
    {
        private readonly MeetingContext _context;

        public MeetingsController(MeetingContext context)
        {
            _context = context;
        }

        //GET: api/Meetings
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Meeting>>> GetMeetings()
        {
            return await _context.Meetings.ToListAsync();
        }

        // GET: api/Meetings/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Meeting>> GetMeeting(string id)
        {
            var meeting = await _context.Meetings.FindAsync(id);

            if (meeting == null)
            {
                return NotFound();
            }

            return meeting;
        }

        // PUT: api/Meetings/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutMeeting(string id, Meeting meeting)
        {
            if (id != meeting.Id)
            {
                return BadRequest();
            }

            _context.Entry(meeting).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MeetingExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Meetings
        [HttpPost]
        public async Task<ActionResult<Meeting>> PostMeeting(Meeting meeting)
        {
            if (ModelState.IsValid)
            {
                Guid obj = Guid.NewGuid();
                meeting.Id = obj.ToString();
                _context.Meetings.Add(meeting);
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (MeetingExists(meeting.Id))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtAction(nameof(GetMeeting), new { id = meeting.Id }, meeting);
        }

        // DELETE: api/Meetings/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<Meeting>> DeleteMeeting(string id)
        {
            var meeting = await _context.Meetings.FindAsync(id);

            if (meeting == null)
            {
                return NotFound();
            }

            _context.Meetings.Remove(meeting);
            await _context.SaveChangesAsync();

            return meeting;
        }

        private bool MeetingExists(string id)
        {
            return _context.Meetings.Any(e => e.Id == id);
        }
    }
}

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-web-api pagination filtering


    【解决方案1】:

    试试看:

    这只是一个示例:

     //GET: api/Meetings
            [HttpGet]
            public async Task<ActionResult<IEnumerable<Meeting>>> GetMeetings(string sort_by, string sort_type, string s, int page , int page_size)
            {
                IQueryable<Meeting> query = _context.Meetings;
                switch (sort_by)
                {
                    case "name":
                        if (sort_type == "asc")
                        {
                            query = query.orderby(c => c.name);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.name);
                        }
    
                        break;
                    case "surname":
                        if (sort_type == "asc")
                        {
                            query = query.orderby(c => c.surname);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.surname);
                        }
    
                        break;
                         //do more
    
    
                }
                //your search 
                if (!string.IsNullOrEmpty(s))
                {
               
                    query = query.where(c => c.name.Contains(s));
                }
    
    
    
    
                return await query.Skip((page - 1)* page_size).Take(page_size).ToListAsync();
            }
    

    【讨论】:

    • 您可以添加一个模型以避免将每个参数分开。
    • @Arcord 他/她想按如下查询字符串进行过滤:localhost:8000/api/…
    • ToListAsync() 出现错误,IEnumerable 不包含“ToListAsync()”的定义
    • 你仍然可以使用模型,你只需要在参数前面使用“[FromQuery]”属性来警告模型绑定器数据将来自查询参数。
    • @Aska 我改变这一行试试看:IQueryable query = _context.Meetings;
    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 2011-06-04
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2017-07-13
    • 1970-01-01
    相关资源
    最近更新 更多