Below you can find typical and some not so typical routes being mapped on controller actions.
This is meant to be a cheat sheet that you can come back and refer to.
public class TestController : Controller
{
// /hello
[Route("/hello")]
public IActionResult Hello()
=> Ok("Hello");
// /hi only GET method
[Route("/hi")]
[HttpGet]
public IActionResult Hi()
=> Ok("Hi");
//Alternative for previous
[HttpGet("/hi")]
public IActionResult Hi()
=> Ok("Hi");
}
//Route prefix
[Route("test")]
public class TestController : Controller
{
//You can have multiple routes on an action
[Route("")] // /test
[Route("hello")] // /test/hello
public IActionResult Hello()
=> Ok("Hello");
// Maps to both:
// /test/hi, and:
// /hi
[Route("/hi")] // Overrides the prefix with /, you can also use ~/
[Route("hi")]
public IActionResult Hi()
=> Ok("Hi");
// /test/greet/Joonas -> maps Joonas to the name parameter
[Route("greet/{name}")]
public IActionResult Greet(string name)
=> Ok($"Hello {name}!");
//Parameters can be optional
// /test/greetopt -> name == null
// /test/greetopt/Joonas -> name == Joonas
[Route("greetopt/{name?}")]
public IActionResult GreetOptional(string name)
=> Ok(name == null ? "No name" : "Hi!");
}
// You can use [controller], [action], and [area] to create generic templates
[Route("[controller]/[action]")]
public class MyController : Controller
{
// /my/info
public IActionResult Info()
=> Ok("Info");
// /my/i
[Route("/[controller]/i")]
public IActionResult Info2()
=> Ok("Info2");
}
[Route("users")]
public class SelectionController : Controller
{
//You can use constraints to influence route selection
//Do not use for validation!
// /users/123
[Route("{id:int}")]
public IActionResult Int(int id)
=> Ok($"Looked up user id {id}");
// /users/joonas
[Route("{name:alpha}")]
public IActionResult String(string name)
=> Ok($"User name {name}");
}