Search code examples
asp.net-web-apiasp.net-coreasp.net-web-api2.net-coreasp.net-web-api-routing

User optional Attribute Route to indicate tenant in dotnet core web api


Is there a way to define optional route parameter for a REST dotnet core webapi project?

I'd like to define an optional tenant parameter within my API controller. If the parameter is present, I'd like to use it to filter my queries.

api.example.com/tenant1/users -> all users of tenant1

api.example.com/users -> all users in the system

 [Route ("{tenant:guid?}/[controller]")]
    public class UsersController {

        // GET api.example.com/{tenant}/users
        [HttpGet]
        public async Task<IActionResult> GetUsers (Guid tenant) {
            ...
            if(tentant != null){
              var users = await _db.Users.GetAllByTentant(tenant);
              return Ok (users);
            } else {
              var users = await _db.Users.GetAll();
              return Ok (users);
            }
        }
}

Solution

  • Tanks to the hint of Yuli

    [Route ("[controller]")]
    public class UsersController {
    
        // GET api.example.com/users
        [HttpGet]
        public async Task<IActionResult> GetUsers () {
            ...
              var users = await _db.Users.GetAll();
              return Ok (users);
        }
    
        // GET api.example.com/{tenant}/users
        [HttpGet("/{tenant}/[controller]")]
        public async Task<IActionResult> GetUsers (Guid tenant) {
            ...
              var users = await _db.Users.GetAllByTentant(tenant);
              return Ok (users);
        }
    }