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

前端 未结 3 1077
感动是毒
感动是毒 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 16:57

    You just need to add the Route to the top of your controller.

    Specify the route with api, controller and action:

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AvailableRoomsController : ControllerBase
    {
    ...
    }
    
    0 讨论(0)
  • 2021-02-15 17:07

    Neither could we do action overloads nor prefix action name as Http verb.The way routing works in ASP.NET Core is different than how it did in ASP.NET Web Api.

    However, you can simply combine these actions and then branch inside, since all params are optional if you send as querystring

    [HttpGet]
    public ActionResult<string> Get(int id, string name)
    {
      if(name == null){..}
      else{...}
    }
    

    Or you need to use attribute routing to specify each api if you send in route data:

    [HttpGet("{id}")]       
    public ActionResult<string> Get(int id)
    {
        return "value";
    }
    
    
    [HttpGet("{id}/{name}")]
    public ActionResult<string> Get(int id, string name)
    {
        return name;
    }
    

    Refer to Attribute Routing,Web Api Core 2 distinguishing GETs

    0 讨论(0)
  • 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<ActionResult<IEnumerable<AvailableRoom>>> GetAvailableRooms()
        {
            return await _context.AvailableRooms.ToListAsync();
        }
    
    
        // POST: api/AvailableRooms
        [HttpPost]
        public async Task<ActionResult<AvailableRoom>> 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.

    0 讨论(0)
提交回复
热议问题