Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() => HTTP DELETE) to have incoming calls appropriately routed.

I also remember that in ASP.NET Web API parameter matching takes place so that even Get(int id) and Get(int id, string name) get automatically and appropriately routed without requiring any attributes.

public class MyController
{
  public ActionResult Get(int id) => ...

  public ActionResult Get(int id, string name) => ...

  public ActionResult DeleteItem(int id) => ...
}

Isn't this all available in ASP.NET Web API Core?

like image 447
AxD Avatar asked Jun 12 '19 14:06

AxD


2 Answers

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
{
...
}
like image 143
Tony Abrams Avatar answered Sep 19 '22 14:09

Tony Abrams


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

like image 25
Ryan Avatar answered Sep 18 '22 14:09

Ryan