ASP.NET Core Web API: Routing by method name?

前端 未结 3 1079
感动是毒
感动是毒 2021-02-15 16:25

I remember from ASP.NET Web API that it\'s sufficient to prefix Web API REST method names with HTTP commands (e.g. GetList() => HTTP GET, Delete(

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-15 17:07

    This is available for Core 2 yes, but the way that I know how to do it is something like this

    [Route("api/[controller]")]
    [ApiController]
    public class AvailableRoomsController : ControllerBase
    {
        private readonly ApplicationContext _context;
    
        public AvailableRoomsController(ApplicationContext context)
        {
            _context = context;
        }
    
        // GET: api/AvailableRooms
        [HttpGet]
        public async Task>> GetAvailableRooms()
        {
            return await _context.AvailableRooms.ToListAsync();
        }
    
    
        // POST: api/AvailableRooms
        [HttpPost]
        public async Task> PostAvailableRoom(AvailableRoom availableRoom)
        {
            _context.AvailableRooms.Add(availableRoom);
            await _context.SaveChangesAsync();
    
            return CreatedAtAction("GetAvailableRoom", new { id = availableRoom.Id }, availableRoom);
        }
    
        [HttpPut] .... etc
    }
    

    Now depending on what kind of REST action you specify and what type of model you send to "api/AvailableRooms" if the proper Action exists it will be chosen.

    Visual Studio 2019 and I think 2017 can create a controller such as this automatically if you right click your Controllers folder and click Add->Controller and then choose "API Controller with actions, using Entity Framework" and choose one of your Model classes.

提交回复
热议问题