When working on a .NET/.NET Core project you might want to keep your route names consistent with the controller name and method name without having to constantly update them if you rename the controllor or method. This is where the controller and action keywords come in.

Suppose we have the following:

[ApiController]
[Route("users")]
public class UserController : ControllerBase
{
    [Route("getuser/{id:int}")]
    public GetUser(int id) {
        return "user " + id;
    }
}

The route will be /users/getuser/{id} with the id being a dynamic value. But what if we decide to do some refactoring and change the name of the controller and method? We would have to change the route names also. Sometimes we might even forget.

This is where the controller and action keywords come in handy. If you change the name of the controller and method(s) within the controller, these keywords adopt the new names of the controller and method(s) with no need to change them manually. Here’s how we would use them if we did some refactoring on the example above:

[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    [Route("[action]/{id:int}")]
    public User(int id) {
        return "user " + id;
    }
}

Now, since we did the refactoring, the route would be /users/user/{id}. We did not need to update the routes manually ousrselves. It was taken care for us using these keywords.