Skip to content

Instantly share code, notes, and snippets.

@Marusyk
Last active November 26, 2018 20:54
Show Gist options
  • Save Marusyk/64dacdcd93ab932e2a14aa50e410840b to your computer and use it in GitHub Desktop.
Save Marusyk/64dacdcd93ab932e2a14aa50e410840b to your computer and use it in GitHub Desktop.
Demonstrates how to route works with abstract base controllers actions and inherited controllers in ASP.NET Core WebAPI
// Example for question https://stackoverflow.com/questions/53488184/asp-net-core-controllers-route-attribute-inheritance-and-abstract-controllers-ac#53488184
public abstract class BaseApiController : Controller
{
[HttpGet]
[Route("")]
public virtual IActionResult GetAll()
{
return Ok("GetAll action from base");
}
[HttpGet]
[Route("{id}")]
public virtual IActionResult GetById(int id)
{
return Ok($"GetById action from base with id: {id}");
}
[HttpPost]
[Route("")]
public virtual IActionResult Insert(string model)
{
return Ok("Insert action from base");
}
}
[Route("api/Student")]
public class StudentController : BaseApiController
{
[HttpGet]
[Route("{id}/ShowNotes")]
public virtual IActionResult ShowNotes(int id)
{
return Ok($"ShowNotes action from Student with id {id}");
}
}
[Route("api/Teacher")]
public class TeacherController : BaseApiController
{
[HttpGet]
[Route("{id}/ShowHours")]
public virtual IActionResult ShowHours(int id)
{
return Ok($"ShowHours action from Teacher with id {id}");
}
}
@Marusyk
Copy link
Author

Marusyk commented Nov 26, 2018

The result:

GET http://localhost:51087/api/Student
GetAll action from base
GET http://localhost:51087/api/Student/1
GetById action from base with id: 1
GET http://localhost:51087/api/Student/1/ShowNotes
ShowNotes action from Student with id 1
GET http://localhost:51087/api/Teacher
GetAll action from base
GET http://localhost:51087/api/Teacher/2
GetById action from base with id: 2
GET http://localhost:51087/api/Teacher/2/ShowHours
ShowHours action from Teacher with id 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment