Full source code available here.
Routing in .NET Core Web Api (1.1 and 2) is a little different than in earlier versions.
I’ve written about this a few times, you can find those posts here.
In this post I’m going to show some examples of routing that might help you if you are having problems, especially if you want to have multiple GET methods. In a later article I will show how to use the action method selector to choose between actions methods with the same signature.
The code and comments are fairly self explanatory.
[HttpGet("api/Person")] public class PersonController : Controller { // GET: api/Person [HttpGet] public IEnumerable<string> Get() { return new string[] { "Dave Smith", "Edward Temple" }; } // http://localhost:27624/api/person/1 [HttpGet("{id}")] public string Get(int id) { return $"Get by id:{id} - Dave Smith"; } // http://localhost:62689/api/person/ByNumber/5 [HttpGet("ByNumber/{number}")] public string GetByNumber(int number) { return $"Get by number:{number} - Tom Davis"; } // http://localhost:62689/api/person/ByFirstName/Steve [HttpGet("ByFirstName")] public string GetByFristName(string firstName) { return $"Get by first name - {firstName} Smith"; } // http://localhost:62689/api/person/ByLastName?lastname=Smith [HttpGet("ByLastName")] public string GetByLastName(string lastName) { return $"Get by last name - Dave {lastName}"; } // http://localhost:62689/api/person/ByFirstAndLastName?firstname=Steve&lastname=Smith [HttpGet("ByFirstAndLastName")] public string GetByFirstAndLastName(string firstName, string lastName) { return $"Get by first and last name - {firstName} {lastName}"; } }
Here are some more examples with attribute routing and a query model.
[HttpGet("api/accounts/{AccountId}")] public class AccountsController : Controller { // http://localhost:62689/api/accounts/11 public IActionResult Get(int accountId) { return Ok(accountId); } // http://localhost:62689/api/accounts/?accountId=11 // http://localhost:62689/api/accounts/?accountId=11&AccountName=dave // http://localhost:62689/api/accounts/?accountId=11&AccountName=dave&managerid=15 [HttpGet("/api/accounts/")] public IActionResult Get(QueryModel queryModel) { return Ok(queryModel); } // http://localhost:62689/api/accounts/11/manager/22 [HttpGet("Manager/{ManagerId}")] public IActionResult Get(int accountId, int managerId) { return Ok($"accountId:{accountId}, managerId:{managerId}"); } // http://localhost:62689/api/accounts/11/manager/22/role/33 [HttpGet("/api/accounts/{AccountId}/Manager/{ManagerId}/Role/{RoleId}")] public IActionResult Get(int accountId, int managerId, int roleId) { return Ok($"accountId:{accountId}, managerId:{managerId}, roleId:{roleId}"); } } public class QueryModel { public int AccountId { get; set; } public string AccountName { get; set; } public int ManagerId { get; set; } }
Full source code available here.